"""The blind second reader's sample (SCHEME.md §6.2): 20 per cent of the coded rows, stratified by source, drawn with a fixed seed.
For each row the reader is given the two places as text and the record's one-line description, and the definitions of SCHEME.md §1 and §3.
It is not given the prediction, the source totals, the first coder's codes, or the source names of the strata beyond what a place
shows of itself. Writes blind_sample.json (for the reader) and blind_key.json (row ids, kept back)."""
import json, random, re, sys, pathlib, pickle, collections
H = pathlib.Path(__file__).resolve().parent; UM = H.parent
sys.argv = [sys.argv[0], "4"]
src = (H / "ops_auto.py").read_text(encoding="utf-8").split("coded = [i for i in F]")[0]
ns = {"__file__": str(H / "ops_auto.py")}; exec(src, ns)
inv, span, srctext, F = ns["inv"], ns["span"], ns["srctext"], ns["F"]
from bridge import hcons
d = pickle.load(open(UM / "dss/dss_words.pkl", "rb")); lab = d["lab"]
byline = collections.defaultdict(list)
for (sc, ln, b, c, v, g, bib, lang) in d["rows"]: byline[ln].append(g)
def scroll_text(ref):
    m = re.match(r"(\S+)\s+(.+)", ref); sc, loc = m.group(1), m.group(2); out = []
    mm = re.search(r"([\w+]+):(\d+)(?:-(?:([\w+]+):)?(\d+))?", loc)
    if not mm: return ""
    col, a = mm.group(1), int(mm.group(2)); z = int(mm.group(4) or a)
    for ln, (s, fr, li) in sorted(lab.items()):
        try: li = int(li)
        except ValueError: continue
        if s == sc and fr == col and a <= li <= z: out.append(f"{s} {fr}:{li} " + " ".join(byline[ln]))
    return "\n".join(out)
random.seed(20261130)
by = collections.defaultdict(list)
for i in sorted(F): by[inv[i]["source"]].append(i)
pick = []
for s, ids in by.items():
    k = max(2, round(0.2 * len(ids))); pick += random.sample(ids, k)
random.shuffle(pick)
sample, key = [], {}
for n, i in enumerate(pick, 1):
    r = inv[i]; st = scroll_text(r["src_ref"]) if r["source"] == "scrolls" else srctext(i)
    sample.append({"row": f"B{n:03d}", "matthew_ref": "Matthew " + r["matt"], "matthew_text": span("Matt", r["matt"]),
                   "source_ref": r["src_ref"], "source_text": (st or "")[:4000], "record_note": r.get("src_text") or r.get("matt_text") or ""})
    key[f"B{n:03d}"] = i
json.dump(sample, open(H / "blind_sample.json", "w"), ensure_ascii=False, indent=1); json.dump(key, open(H / "blind_key.json", "w"), indent=1)
print(len(sample), collections.Counter(inv[i]["source"] for i in pick))
