"""Rebuild RSI tables/figures locally. Python stdlib + existing matplotlib; no network/model calls.
Usage: python build_rsi.py /path/to/RSI
Inputs: four original data/*-sources.json registries plus data/evidence-curation.json.
Outputs: deterministic tables, bibliography, diagram, chronology and validation.
"""
from pathlib import Path
import csv, json, re, hashlib, sys, datetime, platform
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.patches import FancyBboxPatch, FancyArrowPatch

def csv_write(path, rows):
    keys=list(dict.fromkeys(k for r in rows for k in r))
    with path.open("w",newline="",encoding="utf-8") as f:
        w=csv.DictWriter(f,fieldnames=keys);w.writeheader();w.writerows(rows)

def build(root):
    root=Path(root)
    regs={name:json.loads((root/"data"/name).read_text()) for name in
          ["methods-sources.json","metan-sources.json","economics-sources.json","evaluation-sources.json"]}
    cur=json.loads((root/"data/evidence-curation.json").read_text())
    metadata=json.loads((root/"data/verified-metadata.json").read_text())
    verified=metadata["records"]
    crossref=json.loads((root/verified["E03"]["metadata_payload"]).read_text())["message"]
    assert crossref["published-online"]["date-parts"][0]==[2024,8,6]
    rows=[]; originals={}
    groups=[("M",regs["methods-sources.json"]["records"]+regs["metan-sources.json"]["records"]),
            ("E",regs["economics-sources.json"]["sources"]),
            ("V",[r for r in regs["evaluation-sources.json"]["sources"] if r["id"] not in
                  ["huang2024_intrinsic_correction","wijk2025_rebench"]])]
    for prefix, records in groups:
        for i,r in enumerate(records,1):
            sid=f"{prefix}{i:02d}"
            r=json.loads(json.dumps(r)); r.update(cur.get("overrides",{}).get(sid,{})); originals[sid]=r
            url=r.get("primary_url",r.get("record_url",r.get("url","")))
            aid=r.get("arxiv_id","")
            if not aid and "arxiv.org/abs/" in url: aid=url.split("/abs/")[1]
            if aid and not re.search(r"v\d+$",aid): aid+=r.get("version_checked","")
            version=r.get("version",r.get("version_checked",""))
            first=r.get("first_submission_date",r.get("first_submitted",r.get("initial_date","")))
            selected=next((r[k] for k in ["selected_version_date","version_date","date","online_date","published"] if r.get(k)),"")
            publication=r.get("issue_date",r.get("published",r.get("date","")))
            snapshot=r.get("full_text_snapshot",r.get("local_artifact",{}).get("path",r.get("snapshots",{}).get("full_text",{}).get("path","")))
            digest=r.get("full_text_sha256",r.get("local_artifact",{}).get("sha256",r.get("snapshots",{}).get("full_text",{}).get("sha256","")))
            notes=r.get("version_caveat",r.get("caveat",r.get("limitations",r.get("scope_caveat",""))))
            if sid=="E01": first="2026-09-14";selected="2026-09-14";publication=""
            if sid=="E05": publication=""
            if sid=="E02":
                version="CASP institutional September 2026 PDF"
                first=""  # The arXiv counterpart has distinct metadata fields below.
                notes+=" arXiv counterpart metadata independently retrieved; no byte identity assumed. Repository DOI pending registration on landing page."
            if sid=="E04": version="QJE 140(2), published version"; publication="2025-05";selected="2025-02-04"
            if sid=="E03": version="Economic Policy 40(121); author-hosted PDF";publication="2025-01";selected="";notes+=" The October 4 PDF stamp is a download date, not publication or version date."
            if not version: version=r.get("type","primary page")+": accessed 2026-10-11"
            if sid=="M05": notes+=" "+r.get("version_note_addition","")
            main={
                "work_id":sid,"citation_key":sid,"title":r["title"],
                "authors":"; ".join(r["authors"]),"first_submission_date":first,
                "selected_version_date":selected,"publication_date":publication,
                "manuscript_date":r.get("manuscript_date",""),
                "access_date":"2026-10-11","version":version,"arxiv_id":aid,
                "doi":r.get("doi") or "",
                "doi_type":"repository" if str(r.get("doi","")).startswith("10.48550") else ("publisher" if r.get("doi") else ""),
                "primary_url":url,"full_text_url":r.get("full_text_url",r.get("fulltext_url",r.get("pdf_url",url))),
                "venue":r.get("venue",r.get("journal",r.get("series",r.get("publisher",r.get("status",""))))),
                "category":cur["categories"][sid],"changed_component":r.get("changed_component",""),
                "feedback":r.get("verification",""),"loop":r.get("loop",""),"resource_budget":cur["budget_notes"].get(sid,"See source-specific design; no cross-study resource equivalence assumed."),
                "failure_modes":r.get("limitations",r.get("scope_caveat",r.get("caveat",""))),
                "local_snapshot":snapshot,"snapshot_sha256":digest,
                "read_depth":"Relevant full-text sections inspected; not experimental replication",
                "version_notes":notes,
                "input_records":"methods + evaluation (deduplicated)" if sid in ["M11","M12"] else prefix
            }
            if sid=="E01":
                main["version_notes"]+=" "+r["html_date_discrepancy"]
                main["html_manuscript_date"]="2026-09-13"
            if sid=="E02":
                main.update({k:v for k,v in verified[sid].items() if k.startswith("counterpart_")})
                main["metadata_provenance"]="data/verified-metadata.json; provenance/metadata-retrieval-excerpts.txt"
            if sid=="E03":
                main.update({k:verified[sid][k] for k in ["online_publication_date","publication_date","selected_version_date","local_snapshot","snapshot_sha256"]})
                main["metadata_provenance"]=verified[sid]["metadata_payload"]
            
            rows.append(main)
    assert len(rows)==23
    byid={r["work_id"]:r for r in rows}
    claims=[]
    def add(sid,kind,statement,locator,limitation,url=None):
        claims.append({"claim_id":f"C{len(claims)+1:03d}","work_id":sid,"evidence_class":kind,
          "statement":statement,"source_url":url or byid[sid]["full_text_url"],"locator":locator,
          "source_version":byid[sid]["version"],"access_date":"2026-10-11",
          "limitations":limitation,"independently_reproduced":"false",
          "assessment":"Source-supported within stated scope; author result or model, not reproduced"})
    for sid,r in originals.items():
        if sid.startswith("M"):
            for c in r.get("claims",[]):
                add(sid,c.get("type","author_reported_measurement"),c["statement"],c["locator"],
                    r.get("limitations",r.get("caveat","")),c.get("source_url"))
    for sid,kind,statement,locator,limit in cur["extra_claims"]:add(sid,kind,statement,locator,limit)
    # The four input records E1-E7 preserve source detail; the associated Nature correction is not a main work.
    csv_write(root/"data/literature-register.csv",rows)
    supp=cur.get("supplemental",[])
    for s in supp:
        v=verified[s["work_id"]]
        for key in ["title","authors","arxiv_id","date","url"]:
            assert s[key]==v[key], (s["work_id"],key)
        s["selected_version_date"]=v["selected_version_date"]
        s["metadata_provenance"]="data/verified-metadata.json; "+(v.get("local_snapshot") or metadata["retrieval_excerpt"])
        s["local_snapshot"]=v.get("local_snapshot","")
        s["snapshot_sha256"]=v.get("snapshot_sha256","")
    csv_write(root/"data/supplemental-sources.csv",[{**r,"authors":"; ".join(r["authors"]),"access_date":"2026-10-11","read_depth":"Primary metadata and relevant full-text sections","reproduced":"false"} for r in supp])
    for r in supp:
        claims.append({"claim_id":f"C{len(claims)+1:03d}","work_id":r["work_id"],"evidence_class":"source_audit_supplement","statement":r["finding"],"source_url":r["url"].replace("/abs/","/html/"),"locator":r["locator"],"source_version":r["arxiv_id"] or "Primary page accessed 2026-10-11","access_date":"2026-10-11","limitations":r["limit"],"independently_reproduced":"false","assessment":"Supplementary primary evidence; outside 23 main works"})
    for c in claims:
        if c["work_id"]=="M08": c["locator"]="Sections 4.2–4.4; Figure 2 SWE-bench; Section 4.4 full Polyglot"
        if c["work_id"]=="M09" and "selection" in c["statement"].lower():
            c["statement"]="Parent selection fixed in main experiments; Appendix E.5 tests editable selection with no statistically significant advantage."
            c["locator"]="Section 7; Appendix E.5, Figures 11–12"
        if c["work_id"]=="M04": c["statement"]=c["statement"].replace("human demonstration","external SFT demonstration").replace("human-demonstration","external SFT demonstration")
    csv_write(root/"data/claims-evidence.csv",claims)
    chronology=[]
    for r in rows:
        if r["work_id"].startswith("M"):
            chronology.append({"work_id":r["work_id"],"label":originals[r["work_id"]].get("short_name","Meta^n"),
                "first_submission":r["first_submission_date"],"selected_version":r["selected_version_date"],
                "category":r["category"],"source_url":r["primary_url"]})
    csv_write(root/"data/chronology.csv",chronology)
    def esc(s):return str(s).replace("&",r"\&").replace("%",r"\%").replace("_",r"\_").replace("$",r"\$")
    bib=[]
    for r in rows:
        original=originals[r["work_id"]]
        authorlist=original["authors"]
        auth=" and ".join("{"+a+"}" if a=="International Energy Agency" else a for a in authorlist)
        year=(r["publication_date"] or r["first_submission_date"] or r["selected_version_date"])[:4]
        fields={"title":"{"+esc(r["title"])+"}","author":auth,"year":year,"url":r["primary_url"],
                "note":esc(r["version"]+"; accessed 2026-10-11")}
        if r["work_id"]=="M13":
            # Preserve valid math only for the reviewed title, not arbitrary input.
            fields["title"]="{"+esc(r["title"].replace("Meta$^n$","METANPLACEHOLDER")).replace("METANPLACEHOLDER","Meta$^{n}$")+"}"
        if r["doi"]:fields["doi"]=r["doi"]
        if r["arxiv_id"]:fields.update({"eprint":r["arxiv_id"],"archivePrefix":"arXiv"})
        for k in ["journal","volume","pages"]:
            if original.get(k): fields[k]=str(original[k])
        if original.get("issue"):fields["number"]=str(original["issue"])
        bib.append("@"+("article" if original.get("journal") else "misc")+"{"+r["work_id"]+",\n"+
                   "\n".join("  "+k+" = {"+v+"}," for k,v in fields.items())+"\n}")
    bib.append("@misc{V01correction,\n  title = {Author Correction: AI models collapse when trained on recursively generated data},\n  doi = {10.1038/s41586-025-08905-3},\n  year = {2025},\n  url = {https://doi.org/10.1038/s41586-025-08905-3},\n  note = {Associated correction to V01; not a separate main work}\n}")
    for r in supp:
        fields={"title":esc(r["title"]),"author":" and ".join(r["authors"]),"year":r["date"][:4],"url":r["url"],"note":r["scope"]+"; "+(r["arxiv_id"] or r["date"])+"; accessed 2026-10-11"}
        bib.append("@misc{"+r["work_id"]+",\n"+"\n".join("  "+k+" = {"+v+"}," for k,v in fields.items())+"\n}")
    (root/"data/bibliography.bib").write_text("\n\n".join(bib)+"\n")
    plt.rcParams.update({"font.family":"DejaVu Sans","font.size":10,"axes.titlesize":11,"axes.labelsize":10,"svg.fonttype":"none","svg.hashsalt":"rsi-2026-10-11"})
    colors={"Weight learning":"#0072B2","Inference and memory":"#666666","Scaffold and meta-process":"#CC79A7","AI-assisted R&D":"#D55E00","Evaluation":"#009E73"}
    # One row per work avoids coincident 2023 dates and implies no performance ranking.
    fig,ax=plt.subplots(figsize=(10.5,7.8))
    ordered=sorted(chronology,key=lambda r:(r["first_submission"],r["work_id"]))
    for y,r in enumerate(ordered):
        a=datetime.date.fromisoformat(r["first_submission"]);b=datetime.date.fromisoformat(r["selected_version"])
        ax.plot([a,b],[y,y],color=colors[r["category"]],lw=2)
        ax.scatter([a],[y],color=colors[r["category"]],s=36,zorder=3)
        ax.scatter([b],[y],facecolors="white",edgecolors=colors[r["category"]],s=48,zorder=4)
    ax.set_yticks(range(len(ordered)),[r["label"].replace(" / "," /\n") for r in ordered])
    ax.invert_yaxis();ax.set_xlim(datetime.date(2022,1,1),datetime.date(2027,2,1))
    ax.xaxis.set_major_locator(mdates.YearLocator());ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y"))
    ax.set_title("Selected mechanisms, dated by first submission and inspected version",loc="left",pad=15)
    ax.set_xlabel("Calendar year");ax.grid(axis="x",alpha=.2)
    for spine in ["top","right","left"]:ax.spines[spine].set_visible(False)
    ax.tick_params(axis="y",length=0)
    fig.text(.32,.13,"Filled = first submission    Open = inspected version",fontsize=9)
    fig.text(.32,.085,"13 methods/evaluation works; selected corpus, not publication counts.\nColors: blue weights; gray inference; pink scaffold/meta-process;\norange AI-assisted R&D; green evaluation. Coincident dates show one open mark.",fontsize=9,va="top")
    fig.subplots_adjust(left=.32,right=.97,top=.91,bottom=.24)
    geometric=[]; chronology_overlap=[]
    for f,name in [(fig,"methods-chronology")]:
        f.canvas.draw()
        visible=[(t,t.get_window_extent(f.canvas.get_renderer())) for t in f.findobj(matplotlib.text.Text) if t.get_visible() and t.get_text().strip()]
        chronology_overlap=[(a.get_text(),b.get_text()) for i,(a,ba) in enumerate(visible) for b,bb in visible[i+1:] if ba.overlaps(bb)]
        for t in f.findobj(matplotlib.text.Text):
            if t.get_visible() and t.get_text().strip():
                b=t.get_window_extent(f.canvas.get_renderer())
                if b.x0<0 or b.y0<0 or b.x1>f.bbox.width or b.y1>f.bbox.height:geometric.append(name+":"+t.get_text())
        f.savefig(root/f"figures/{name}.png",dpi=180)
        f.savefig(root/f"figures/{name}.svg",metadata={"Date":None})
    plt.close(fig)
    # Conceptual model: edges denote mechanisms, never measured elasticity.
    fig,ax=plt.subplots(figsize=(11.5,7.3));ax.set_xlim(0,12);ax.set_ylim(0,8);ax.axis("off")
    boxes={
     "Capability":(1,5.7,2.5,1.0,"AI capability\nmodel + scaffold","#D9EAF4"),
     "Research":(4.8,5.7,2.5,1.0,"AI-assisted R&D\npropose, test, validate","#EDE3EF"),
     "Efficiency":(8.6,5.7,2.5,1.0,"Algorithmic efficiency\nverified useful methods","#F7E4D8"),
     "Local":(1,2.9,2.5,1.25,"Local updates\nanswers / memory\nweights / agent code","#EFEFEF"),
     "Inputs":(4.8,2.9,2.5,1.25,"External inputs\ncompute, data, people\nverifiers, energy","#EFEFEF"),
     "Economy":(8.6,2.9,2.5,1.25,"Economic adoption\ncomplements, institutions\nproductivity and welfare","#EFEFEF")}
    for x,y,w,h,label,col in boxes.values():
        ax.add_patch(FancyBboxPatch((x,y),w,h,boxstyle="round,pad=0.08",fc=col,ec="#555555",lw=1))
        ax.text(x+w/2,y+h/2,label,ha="center",va="center",fontsize=10)
    def arrow(start,end,dashed=False,rad=0):
        ax.add_patch(FancyArrowPatch(start,end,arrowstyle="-|>",mutation_scale=14,lw=1.6,color="#444444",
             linestyle="--" if dashed else "-",connectionstyle=f"arc3,rad={rad}"))
    arrow((3.6,6.2),(4.7,6.2));arrow((7.4,6.2),(8.5,6.2))
    arrow((9.85,6.85),(2.25,6.85),True,rad=.13)
    ax.text(6,7.64,"Successor capability requires verified pass-through",ha="center",fontsize=10)
    arrow((2.25,4.25),(2.25,5.6))
    arrow((6.05,4.25),(6.05,5.6))
    arrow((9.85,5.6),(9.85,4.25),True)
    arrow((8.5,3.5),(7.4,3.5),True)
    ax.text(6,.95,"Solid: specified local mechanisms     Dashed: conditional wider feedback\nArrows are conceptual, not estimated causal effects or measured loop closure.",ha="center",fontsize=10)
    ax.text(6,2.08,"Audit the improver separately: can the successor produce better changes\non fresh targets at the same total resource budget?",ha="center",fontsize=10)
    fig.subplots_adjust(left=.02,right=.98,top=.98,bottom=.02)
    fig.canvas.draw()
    visible=[(t,t.get_window_extent(fig.canvas.get_renderer())) for t in fig.findobj(matplotlib.text.Text) if t.get_visible() and t.get_text().strip()]
    overlap=[(a.get_text(),b.get_text()) for i,(a,ba) in enumerate(visible) for b,bb in visible[i+1:] if ba.overlaps(bb)]
    for t,b in visible:
        if b.x0<0 or b.y0<0 or b.x1>fig.bbox.width or b.y1>fig.bbox.height:geometric.append("feedback:"+t.get_text())
    arrow_text_intersections=[]
    for p in ax.patches:
        if isinstance(p,FancyArrowPatch):
            path=p.get_transform().transform_path(p.get_path())
            # Evaluate drawn segments, excluding CLOSEPOLY's dummy vertex.
            segments=[]; previous=None; start=None
            for vertices,code in path.iter_segments(curves=False):
                point=vertices[-2:]
                if code==matplotlib.path.Path.MOVETO:
                    previous=point;start=point
                elif code==matplotlib.path.Path.CLOSEPOLY:
                    if previous is not None:
                        segments.append(matplotlib.path.Path([previous,start]))
                    previous=start
                elif code==matplotlib.path.Path.LINETO:
                    if previous is not None:
                        segments.append(matplotlib.path.Path([previous,point]))
                    previous=point
            for t,b in visible:
                if any(segment.intersects_bbox(b,filled=False) for segment in segments):
                    arrow_text_intersections.append(t.get_text())
    fig.savefig(root/"figures/feedback-diagram.png",dpi=180)
    fig.savefig(root/"figures/feedback-diagram.svg",metadata={"Date":None});plt.close(fig)
    # Validate explicit project references; no host-wide discovery.
    import shutil
    import xml.etree.ElementTree as ET
    for name in ["feedback-diagram.png","methods-chronology.png"]:
        shutil.copyfile(root/"figures"/name,root/"reports"/name)
    inputs=[]
    def record(rel):
        p=root/rel
        return {"path":str(rel),"bytes":p.stat().st_size,"sha256":hashlib.sha256(p.read_bytes()).hexdigest()}
    dependency_paths=["data/"+n for n in regs]+["data/evidence-curation.json","data/verified-metadata.json","reports/build_rsi.py",metadata["retrieval_excerpt"],verified["E03"]["metadata_payload"]]
    missing=[];mismatches=[]
    for r in rows+supp:
        if r["local_snapshot"]:
            p=root/r["local_snapshot"]
            if not p.exists():missing.append(r["work_id"]);continue
            h=hashlib.sha256(p.read_bytes()).hexdigest()
            if r["snapshot_sha256"] and h!=r["snapshot_sha256"]:mismatches.append(r["work_id"])
            dependency_paths.append(r["local_snapshot"])
    inputs=[record(p) for p in dict.fromkeys(dependency_paths)]
    input_records=sum(len(r.get("records",r.get("sources",[]))) for r in regs.values())
    bibkeys=re.findall(r"^@\w+\{([^,]+),",(root/"data/bibliography.bib").read_text(),re.M)
    assert len(set(byid))==len(rows)==23
    assert len({c["claim_id"] for c in claims})==len(claims)
    assert len(set(bibkeys))==len(bibkeys)
    assert set(bibkeys)==set(byid)|{s["work_id"] for s in supp}|{"V01correction"}
    assert all(any(c["work_id"]==wid for c in claims) for wid in byid)
    assert len({r["work_id"] for r in chronology})==len(chronology)
    assert all(r["first_submission"]==byid[r["work_id"]]["first_submission_date"] and r["selected_version"]==byid[r["work_id"]]["selected_version_date"] for r in chronology)
    assert byid["E01"]["first_submission_date"]=="2026-09-14" and byid["E01"]["manuscript_date"]=="2026-09-15"
    assert "Meta$^{n}$" in (root/"data/bibliography.bib").read_text()
    unknown=sorted(set(c["work_id"] for c in claims)-set(byid)-set(r["work_id"] for r in supp))
    reports=["rsi-survey.md","methods-taxonomy.md","research-agenda.md","review-results.md","artifact-index.md"]
    missing_links=[]
    for name in reports:
        p=root/"reports"/name
        for link in re.findall(r"!\[[^]]*\]\(([^)]+)\)",p.read_text()):
            if not link.startswith(("https://","http://")) and not (p.parent/link).exists():missing_links.append(name+":"+link)
    for name in ["feedback-diagram","methods-chronology"]:
        ET.parse(root/f"figures/{name}.svg")
        assert (root/f"reports/{name}.png").read_bytes()==(root/f"figures/{name}.png").read_bytes()
    checks={"unique_main_works":len(rows),"input_records":input_records,"duplicates_merged":input_records-len(rows),
       "claims":len(claims),"bibliography_main_entries":len(set(bibkeys)&set(byid)),
       "associated_corrections":len(set(bibkeys)-set(byid)-{s["work_id"] for s in supp}),
       "chronology_works":len(chronology),"registered_main_snapshot_count":sum(bool(r["local_snapshot"]) for r in rows),
       "main_works_without_local_snapshot":[r["work_id"] for r in rows if not r["local_snapshot"]],
       "supplemental_local_snapshot_count":sum(bool(r["local_snapshot"]) for r in supp),
       "supplemental_works_without_local_snapshot":[r["work_id"] for r in supp if not r["local_snapshot"]],
       "correction_without_local_snapshot":["V01correction"],
       "missing_registered_snapshots":missing,"snapshot_hash_mismatches":mismatches,
       "supplemental_works":len(supp),"bibliography_total_entries":len(bibkeys),
       "unknown_claim_work_ids":unknown,"missing_local_figure_links":missing_links,
       "figure_out_of_bounds":geometric,"feedback_text_overlaps":overlap,
       "chronology_text_overlaps":chronology_overlap,"feedback_arrow_text_intersections":arrow_text_intersections,
       "figure_check_scope":"Agg text bounding boxes, pairwise text overlaps and path/text-box intersections; SVG XML parse. Visual inspection remains required; renderer/font differences not exhaustively checked.",
       "python":platform.python_version(),"matplotlib":matplotlib.__version__,
       "build_only_network_calls":0,"build_only_model_calls":0,"experiments_executed":0,
       "workflow_scope_note":"Zero calls refers only to this offline builder, not the primary-source web research or delegated review.",
       "report_sha256":{name:record("reports/"+name)["sha256"] for name in reports},
       "check_scope":"Calculated/asserted table relationships, explicit dependency and output hashes; not primary-result replication or complete source preservation.",
       "calibration_arithmetic":{"log_threshold":1/6.5,"compounded_threshold":__import__("math").expm1(1/6.5),"log_uplift":__import__("math").log(4)/16,"compounded_uplift":__import__("math").expm1(__import__("math").log(4)/16)}}
    assert not any([missing,mismatches,geometric,overlap,chronology_overlap,arrow_text_intersections,unknown,missing_links]),checks
    (root/"provenance/input-checksums.json").write_text(json.dumps(inputs,indent=2)+"\n")
    (root/"provenance/validation.json").write_text(json.dumps(checks,indent=2)+"\n")
    output_paths=["data/"+n for n in ["literature-register.csv","claims-evidence.csv","supplemental-sources.csv","chronology.csv","bibliography.bib"]]+["figures/"+n+ext for n in ["feedback-diagram","methods-chronology"] for ext in [".png",".svg"]]+["reports/"+n for n in reports]+["reports/feedback-diagram.png","reports/methods-chronology.png","provenance/input-checksums.json","provenance/validation.json"]
    output_manifest={"scope":"Current derived files and authored reports. Excludes this manifest and archive to avoid self-reference; archive validated separately.","files":[record(p) for p in output_paths]}
    (root/"provenance/output-checksums.json").write_text(json.dumps(output_manifest,indent=2)+"\n")
    return checks
if __name__=="__main__":
    print(json.dumps(build(Path(sys.argv[1])),indent=2))
