"""Reproduce the sample and score the screening run for literature-screening-triage.
Data: SYNERGY dataset, review Smid_2020 (CC0 1.0), https://github.com/asreview/synergy-dataset
Titles/abstracts come from the OpenAlex API (CC0 metadata). No personal data is sent.

Usage:
  python literature-screening-triage_recompute.py sample  WORKDIR   # download ids.csv, fetch OpenAlex, draw sample, write WORKDIR/records.json
  python literature-screening-triage_recompute.py score   WORKDIR OUTPUT.txt   # score a model output against the key
Key rule (stated, see page): a record is INCLUDED if ANY row of ids.csv with its OpenAlex ID has label_included = 1.
Pool = unique OpenAlex IDs that the OpenAlex API still returns with a title. Seed below.
"""
import csv, json, os, random, re, sys, time, urllib.request

SEED = 20261021
N_EXCLUDED = 53          # all 27 included + 53 random excluded = 80
RAW = "https://raw.githubusercontent.com/asreview/synergy-dataset/master/datasets/Smid_2020/Smid_2020_ids.csv"

def inv(ii):
    if not ii: return ""
    pos = {p: w for w, ps in ii.items() for p in ps}
    return " ".join(pos[k] for k in sorted(pos))

def sample(work):
    os.makedirs(work, exist_ok=True)
    p = os.path.join(work, "ids.csv")
    if not os.path.exists(p): urllib.request.urlretrieve(RAW, p)
    rows = list(csv.DictReader(open(p, encoding="utf-8")))
    ids = sorted({r["openalex_id"].split("/")[-1] for r in rows if r["openalex_id"]})
    key = {}
    for r in rows:
        k = r["openalex_id"].split("/")[-1]
        if k: key[k] = max(key.get(k, 0), int(r["label_included"]))
    oa = {}
    for i in range(0, len(ids), 50):
        b = ids[i:i+50]
        u = ("https://api.openalex.org/works?per-page=50&select=id,title,publication_year,type,abstract_inverted_index,doi&filter=openalex_id:" + "|".join(b))
        for w in json.load(urllib.request.urlopen(u, timeout=60))["results"]:
            if w["title"]:
                oa[w["id"].split("/")[-1]] = dict(title=w["title"], year=w["publication_year"], type=w["type"], doi=w["doi"], abstract=inv(w["abstract_inverted_index"]))
        time.sleep(0.3)
    pool_inc = sorted(k for k in oa if key[k] == 1)
    pool_exc = sorted(k for k in oa if key[k] == 0)
    rng = random.Random(SEED)
    exc = rng.sample(pool_exc, N_EXCLUDED)
    sel = pool_inc + exc
    rng.shuffle(sel)
    recs = [dict(id=k, key=key[k], **oa[k]) for k in sel]
    json.dump(recs, open(os.path.join(work, "records.json"), "w", encoding="utf-8"), indent=1)
    print("pool included", len(pool_inc), "pool excluded", len(pool_exc), "sample", len(recs),
          "rows with no OpenAlex ID (no title available):", sum(1 for r in rows if not r["openalex_id"]))

def parse(text):
    """Parse the model's overall labels. Expects table rows containing a W-id and a final label INCLUDE/EXCLUDE/UNSURE in the 'overall' column."""
    lab = {}
    for line in text.splitlines():
        m = re.search(r"\b(W\d{6,})\b", line)
        if not m or "|" not in line: continue
        cells = [c.strip().strip("*") for c in line.strip().strip("|").split("|")]
        for c in cells[1:]:
            if c.upper() in ("INCLUDE", "EXCLUDE", "UNSURE"):
                lab[m.group(1)] = c.upper()   # last matching cell wins (overall column is after layer columns)
    return lab

def score(work, outp):
    recs = json.load(open(os.path.join(work, "records.json"), encoding="utf-8"))
    lab = parse(open(outp, encoding="utf-8").read())
    miss = [r["id"] for r in recs if r["id"] not in lab]
    t = {}
    for r in recs:
        l = lab.get(r["id"], "MISSING")
        t[(r["key"], l)] = t.get((r["key"], l), 0) + 1
    print("records", len(recs), "parsed", len(lab), "missing", miss)
    print("key  | INCLUDE EXCLUDE UNSURE MISSING")
    for k in (1, 0):
        print(" ", k, " |", *[t.get((k, l), 0) for l in ("INCLUDE", "EXCLUDE", "UNSURE", "MISSING")])
    inc_total = sum(1 for r in recs if r["key"] == 1)
    exc_total = len(recs) - inc_total
    kept = lambda k: sum(t.get((k, l), 0) for l in ("INCLUDE", "UNSURE"))
    print("true includes sent to INCLUDE or UNSURE (kept for human):", kept(1), "of", inc_total)
    print("true includes labelled EXCLUDE (lost):", t.get((1, "EXCLUDE"), 0))
    print("true excludes labelled EXCLUDE:", t.get((0, "EXCLUDE"), 0), "of", exc_total)
    print("INCLUDE-only (strict) sensitivity:", t.get((1, "INCLUDE"), 0), "/", inc_total)

if __name__ == "__main__":
    if sys.argv[1] == "sample": sample(sys.argv[2])
    else: score(sys.argv[2], sys.argv[3])
