#!/usr/bin/env python3
"""Check every curated count against three independent transcriptions of Mendel (1866),
and check Mendel's own printed arithmetic (totals and ratios).

Witnesses (data/raw/):
  MW  mendel_1866_de_mendelweb.txt              MendelWeb German transcription (Latin-1)
  IA  mendel_1866_de_internet_archive_ocr.txt   uncorrected OCR of the Smithsonian Libraries copy
  DTA mendel_1866_de_dta_onepagepapers.html     Deutsches Textarchiv double-keyed transcription,
                                                as served by onepagepapers.com (CC BY-SA 4.0)
Outputs: results/source_verification.csv, results/source_verification_summary.json
"""
import csv, html, json, pathlib, re

ROOT = pathlib.Path(__file__).resolve().parents[1]
RAW, CUR, RES = ROOT / "data/raw", ROOT / "data/curated", ROOT / "results"
RES.mkdir(exist_ok=True)

def norm(t):
    t = t.replace(" ", " ")
    t = re.sub(r"(\d),(\d)", r"\1.\2", t)      # German decimal comma -> point
    t = re.sub(r"\s*:\s*", ":", t)             # "2,95 :1" -> "2.95:1"
    return re.sub(r"\s+", " ", t)

def load():
    w = {}
    w["MW"] = norm((RAW / "mendel_1866_de_mendelweb.txt").read_text(encoding="latin-1"))
    w["IA"] = norm((RAW / "mendel_1866_de_internet_archive_ocr.txt").read_text(encoding="utf-8"))
    h = (RAW / "mendel_1866_de_dta_onepagepapers.html").read_text(encoding="utf-8")
    h = re.sub(r"(?is)<(script|style)\b.*?</\1>", " ", h)
    w["DTA"] = norm(html.unescape(re.sub(r"<[^>]+>", " ", h)))
    return w

def window(text, start_pat, end_pat, pad=60):
    a = re.search(start_pat, text)
    if not a:
        return ""
    b = re.search(end_pat, text[a.start():])
    if not b:
        return ""
    return text[max(0, a.start() - 400): a.start() + b.end() + pad]

def has(win, tok):
    return re.search(r"(?<![\d.])" + re.escape(str(tok)) + r"(?!\d)", win) is not None

def rows_csv(name):
    with open(CUR / name, encoding="utf-8") as f:
        return list(csv.DictReader(f))

def main():
    W = load()
    f2 = rows_csv("mendel_f2_monohybrid.csv")
    f3 = rows_csv("mendel_f3_progeny_tests.csv")
    t10 = rows_csv("mendel_first10_plants.csv")
    out = []

    wins_f2 = {k: window(t, r"7324", r"2\.98:1") for k, t in W.items()}
    wins_f3 = {k: window(t, r"565 P\w+", r"65:35") for k, t in W.items()}

    for r in f2:
        e = r["experiment"]
        items = [("total", r["n_total_printed"]), ("dominant", r["dominant"]), ("recessive", r["recessive"]),
                 ("printed ratio", f"{float(r['printed_ratio']):.2f}:1")]
        if r["n_hybrid_parents"]:
            items.append(("hybrid parents", r["n_hybrid_parents"]))
        for what, tok in items:
            out.append({"section": "F2 single-character", "item": f"Expt {e} {what}", "value": tok,
                        **{k: has(wins_f2[k], tok) for k in W}})
    out.append({"section": "F2 single-character", "item": "pooled printed ratio", "value": "2.98:1",
                **{k: has(wins_f2[k], "2.98:1") for k in W}})

    for r in f3:
        e = r["experiment"]
        if e in ("1", "2"):
            ratio = "1.93:1" if e == "1" else "2.13:1"
            for what, tok in [("plants tested", r["n_plants_tested"]), ("constant", r["constant_dominant"]),
                              ("segregating", r["segregating"]), ("printed ratio", ratio)]:
                out.append({"section": "F3 progeny tests", "item": f"Expt {e} {what}", "value": tok,
                            **{k: has(wins_f3[k], tok) for k in W}})
        elif e == "5-repeat":
            for tok in ("65:35", "60:40"):
                out.append({"section": "F3 progeny tests", "item": "Expt 5 repeat, printed ratio", "value": tok,
                            **{k: has(wins_f3[k], tok) for k in W}})
        else:
            a, b = r["constant_dominant"], r["segregating"]
            pat = rf"{e}\. Versuch\W.{{0,40}}?(?<!\d){a} P\w+.{{0,170}}?(?<!\d){b}(?!\d)"
            out.append({"section": "F3 progeny tests", "item": f"Expt {e} constant then segregating (in order)",
                        "value": f"{a} / {b}", **{k: re.search(pat, wins_f3[k]) is not None for k in W}})
    out.append({"section": "F3 progeny tests", "item": "plants selected per experiment (Expts 3-7)", "value": "100",
                **{k: re.search(r"(?<!\d)100 P\w+ ausgew", wins_f3[k]) is not None for k in W}})
    out.append({"section": "F3 progeny tests", "item": "seeds sown per plant (Expts 3-7)", "value": "10 Samen",
                **{k: re.search(r"von jeder 10 Samen", wins_f3[k]) is not None for k in W}})

    for r in t10:
        seq = f"{r['round']} {r['wrinkled']} {r['yellow']} {r['green']}"
        out.append({"section": "First ten plants", "item": f"plant {r['plant']} (round wrinkled yellow green)", "value": seq,
                    **{k: re.search(r"(?<!\d)" + seq + r"(?!\d)", wins_f2[k]) is not None for k in W}})

    for o in out:
        n = sum(bool(o[k]) for k in W)
        o["witnesses_agreeing"] = n
        o["status"] = "confirmed by all three" if n == 3 else ("confirmed by two" if n == 2 else "NOT CONFIRMED")
    with open(RES / "source_verification.csv", "w", encoding="utf-8", newline="") as f:
        w = csv.DictWriter(f, fieldnames=["section", "item", "value", "MW", "IA", "DTA", "witnesses_agreeing", "status"], lineterminator="\n")
        w.writeheader(); w.writerows(out)

    # Mendel's own arithmetic
    arith = []
    for r in f2:
        d, c, n = int(r["dominant"]), int(r["recessive"]), int(r["n_total_printed"])
        arith.append({"check": f"Expt {r['experiment']}: dominant + recessive = printed total", "ok": d + c == n, "detail": f"{d} + {c} = {d + c} (printed {n})"})
        arith.append({"check": f"Expt {r['experiment']}: dominant / recessive rounds to printed ratio", "ok": abs(round(d / c, 2) - float(r["printed_ratio"])) < 1e-9, "detail": f"{d}/{c} = {d / c:.4f} (printed {r['printed_ratio']})"})
    D = sum(int(r["dominant"]) for r in f2); C = sum(int(r["recessive"]) for r in f2)
    arith.append({"check": "pooled ratio rounds to printed 2.98", "ok": round(D / C, 2) == 2.98, "detail": f"{D}/{C} = {D / C:.4f}"})
    for r in f3:
        n, a, b = int(r["n_plants_tested"]), int(r["constant_dominant"]), int(r["segregating"])
        arith.append({"check": f"F3 Expt {r['experiment']}: constant + segregating = plants tested", "ok": a + b == n, "detail": f"{a} + {b} = {a + b} (printed {n})"})
    arith.append({"check": "F3 Expt 1 ratio rounds to printed 1.93", "ok": round(372 / 193, 2) == 1.93, "detail": f"{372 / 193:.4f}"})
    arith.append({"check": "F3 Expt 2 ratio rounds to printed 2.13", "ok": round(353 / 166, 2) == 2.13, "detail": f"{353 / 166:.4f}"})

    not_all = [o for o in out if o["witnesses_agreeing"] < 3]
    summary = {
        "n_items_checked": len(out),
        "confirmed_by_all_three": sum(o["witnesses_agreeing"] == 3 for o in out),
        "confirmed_by_two": sum(o["witnesses_agreeing"] == 2 for o in out),
        "not_confirmed": sum(o["witnesses_agreeing"] < 2 for o in out),
        "items_missing_in_one_witness": [{"item": o["item"], "value": o["value"], "missing_in": [k for k in W if not o[k]]} for o in not_all],
        "arithmetic_checks": arith,
        "arithmetic_all_ok": all(a["ok"] for a in arith),
    }
    (RES / "source_verification_summary.json").write_text(json.dumps(summary, indent=2, ensure_ascii=False), encoding="utf-8")
    print(json.dumps({k: summary[k] for k in ("n_items_checked", "confirmed_by_all_three", "confirmed_by_two", "not_confirmed", "arithmetic_all_ok")}, indent=1))
    for it in summary["items_missing_in_one_witness"]:
        print("  not found:", it)

if __name__ == "__main__":
    main()
