"""Build the local Wave 15 human form from independently verified, pinned inputs.
Existing offline ADV form architecture retained. No corpus imports or writes.
"""
import ast
import base64
import hashlib
import html
import json
from pathlib import Path

HERE = Path(__file__).resolve().parent
VERSION = "15.1.0"
SCOPE = "wave15_exact_selected_answers_and_truth_annotations_not_full_gold_or_promotion"
def sha(raw):
    return hashlib.sha256(raw).hexdigest()
def esc(value):
    return html.escape(str(value), quote=True)
def label(value):
    return value.replace("_", " ").capitalize()
def load_unique(raw):
    def pairs(rows):
        result = {}
        for k, v in rows:
            if k in result:
                raise ValueError("Duplicate JSON key: " + k)
            result[k] = v
        return result
    return json.loads(raw, object_pairs_hook=pairs, parse_constant=lambda s: (_ for _ in ()).throw(ValueError(s)))
def pinned(path, expected, sources):
    raw = Path(path).read_bytes()
    if sha(raw) != expected:
        raise ValueError("Pinned input changed: " + str(path))
    sources[str(path)] = expected
    return load_unique(raw)
def build_bundle():
    config = load_unique((HERE / "INPUT_PINS.json").read_bytes())
    sources = {}
    cp = pinned(config["composition"]["path"], config["composition"]["sha256"], sources)
    verified = pinned(config["verification"]["path"], config["verification"]["sha256"], sources)
    if verified.get("errors") or verified.get("composition_sha256") != config["composition"]["sha256"]:
        raise ValueError("No matching passing independent composition receipt")
    corpus = Path(config["corpus"])
    r1 = pinned(config["r1"]["path"], config["r1"]["sha256"], sources)
    r2 = pinned(config["r2"]["path"], config["r2"]["sha256"], sources)
    f34 = pinned(config["f34"]["path"], config["f34"]["sha256"], sources)
    mac = pinned(config["mac"]["path"], config["mac"]["sha256"], sources)
    defs_path = corpus / "src/kredo_drift_api/dimension_content.py"
    defs_raw = defs_path.read_bytes()
    if sha(defs_raw) != config["definitions_sha256"]:
        raise ValueError("Definitions changed")
    sources[str(defs_path)] = sha(defs_raw)
    definitions = None
    for node in ast.parse(defs_raw).body:
        if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.target.id == "DIMENSION_CONTENT":
            definitions = ast.literal_eval(node.value)
        elif isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == "DIMENSION_CONTENT" for t in node.targets):
            definitions = ast.literal_eval(node.value)
    if not isinstance(definitions, dict):
        raise ValueError("Missing literal definitions")
    source_objects, physical, expected_slots = {}, {}, set()
    for slot in cp["slots"]:
        rel = Path(slot["source_path"])
        if rel.is_absolute() or ".." in rel.parts or rel.parent.as_posix() != "gold_responses/v1/drafts/wave_15":
            raise ValueError("Source path outside exact wave")
        if slot["prompt_id"] not in source_objects:
            obj = pinned(corpus / rel, slot["source_file_sha256"], sources)
            if obj["prompt_id"] != slot["prompt_id"] or sha(obj["prompt_text"].encode()) != slot["prompt_sha256"]:
                raise ValueError("Prompt binding")
            source_objects[obj["prompt_id"]] = obj
            for r in obj["positive_responses"] + obj["near_miss_controls"] + obj["negative_controls"]:
                if r["response_id"] in physical or sha(r["response_text"].encode()) != r["response_sha256"]:
                    raise ValueError("Duplicate or unbound response")
                physical[r["response_id"]] = r
                expected_slots.update((r["response_id"], d) for d in r["applicable_dimensions"])
    maps = {(rid, d): json.loads(json.dumps(r["semantic_adjudication"]["by_dimension"][d]))
            for rid, r in physical.items() for d in r["applicable_dimensions"]}
    for row in r2["negative_map_proposals"] + r2["alternate_map_proposals"]:
        target = maps[(row["response_id"], row["lens"])]
        for field in ("expected", "prohibited"):
            if "proposed_" + field in row:
                target[field] = row["proposed_" + field]
    for row in f34["expected_map_proposals"]:
        target = maps[(row["response_id"], row["lens"])]
        for field in ("expected", "prohibited"):
            for diff in row["map_differences_" + field]:
                target[field][diff["index"]] = row["proposed_" + field][diff["index"]]
    candidates = {x["original_response_id"]: x for x in mac["entries"]}
    for rid, candidate in candidates.items():
        maps[(rid, candidate["lens"])] = {f: candidate["proposed_" + f] for f in ("expected", "prohibited")}
    seen = set()
    prepared = {}
    for s in cp["slots"]:
        key = (s["response_id"], s["lens"])
        if key in seen or key not in expected_slots:
            raise ValueError("Duplicate/extra composed pair")
        seen.add(key)
        r = physical[s["response_id"]]
        candidate = candidates.get(r["response_id"])
        text = candidate["response_text"] if candidate else r["response_text"]
        selected_id = candidate["candidate_response_id"] if candidate else r["response_id"]
        if sha(text.encode()) != s["chosen_text"]["response_sha256"]:
            raise ValueError("Unreviewed chosen text")
        target = maps[key]
        lens = next(x for x in source_objects[s["prompt_id"]]["lens_annotations"] if x["dimension"] == s["lens"])
        for f in ("expected", "prohibited"):
            if [x["judgment"] for x in target[f]] != s["composed_" + f]:
                raise ValueError("Independent map does not match composition: " + str(key))
            if [x["element"] for x in target[f]] != lens[f + "_elements"]:
                raise ValueError("Criterion mismatch")
        record = prepared.setdefault(r["response_id"], dict(response_id=selected_id, original_response_id=r["response_id"],
            response_kind=r["response_kind"], response_text=text, response_sha256=sha(text.encode()),
            history=r if candidate else None, by_dimension={}, issues=[], candidate=bool(candidate)))
        record["by_dimension"][s["lens"]] = target
        record["issues"].extend(s.get("partial", []) + s.get("prompt_binding", []) + s.get("pending", []))
    if seen != expected_slots or len(source_objects) != cp["counts"]["prompts"]:
        raise ValueError("Incomplete all-lens composition")
    items = []
    for pid, obj in source_objects.items():
        rows = [prepared[r["response_id"]] for r in obj["positive_responses"] + obj["near_miss_controls"] + obj["negative_controls"]]
        dimensions = list(dict.fromkeys(d for r in rows for d in r["by_dimension"]))
        items.append(dict(prompt_id=pid, prompt=obj["prompt_text"], prompt_sha256=obj["prompt_sha256"],
            lenses={d: {f: next(x for x in obj["lens_annotations"] if x["dimension"] == d)[f + "_elements"]
                       for f in ("expected", "prohibited")} for d in dimensions},
            definitions={d: definitions[d] for d in dimensions}, responses=rows))
    return dict(schema="kredo.wave15.review-bundle.v1", interface_version=VERSION, review_scope=SCOPE,
        authority="human_review_of_selected_examples_and_truth_maps_only", applied=False, promotion_authorized=False,
        composition_sha256=config["composition"]["sha256"], sources=sources, items=items,
        counts=dict(prompts=len(items), physical_answers=len(prepared), answer_lens_pairs=len(seen),
                    prompt_lens_pairs=sum(len(i["lenses"]) for i in items)),
        held_not_in_review=cp.get("held_not_in_pin", r1["held_not_redrafted"]))
def response_html(r):
    negative = r["response_kind"] in ("near_miss", "negative_control")
    expected_gap = any(x["judgment"] != "present" for a in r["by_dimension"].values() for x in a["expected"])
    prohibited = any(x["judgment"] != "absent" for a in r["by_dimension"].values() for x in a["prohibited"])
    issue = bool(r["issues"]) or expected_gap or prohibited
    if negative:
        status = "Intended failing / boundary example — review whether the evidence supports that role"
    elif issue:
        status = "Positive-category draft with gaps or uncertainty — not a confirmed full positive"
    else:
        status = "All listed expected elements present; listed prohibited elements absent — review still required"
    text = '<article class="answer"><h4>' + esc(label(r["response_kind"])) + '</h4>'
    text += '<p class="status-chip' + (' partial' if issue else '') + '">' + esc(status) + '</p>'
    if r["candidate"]:
        text += '<p class="caption">New independently reviewed candidate, not yet human-approved. Original retained below.</p>'
    text += '<blockquote>' + esc(r["response_text"]) + '</blockquote>'
    if r["issues"]:
        reasons = list(dict.fromkeys(x.get("reason", x.get("note", x.get("status", "Unresolved binding"))) for x in r["issues"]))
        text += '<ul class="issue-list">' + ''.join('<li>' + esc(x) + '</li>' for x in reasons) + '</ul>'
    text += '<details><summary>Element-by-element judgments and their recorded reasons</summary>'
    for dim, groups in r["by_dimension"].items():
        text += '<h5>' + esc(label(dim)) + '</h5><table class="judgments"><thead><tr><th>Criterion</th><th>Observed judgment</th><th>Recorded reason</th></tr></thead><tbody>'
        for f in ("expected", "prohibited"):
            for i, row in enumerate(groups[f]):
                reason = row.get("evidence") or "No separate rationale recorded; compare the displayed answer with this criterion."
                text += '<tr><td><code>' + ("E" if f == "expected" else "P") + str(i) + '</code> ' + esc(row["element"]) + '</td><td>' + esc(row["judgment"]) + '</td><td>' + esc(reason) + '</td></tr>'
        text += '</tbody></table>'
    text += '<p class="caption">Present / absent describe whether the behavior appears. A prohibited behavior being present is a defect, not a pass. Ambiguous includes partial compound criteria. These annotations are not scores.</p></details>'
    if r["history"]:
        text += '<details class="history"><summary>Preserved original answer — outside the new-candidate choice</summary><blockquote>' + esc(r["history"]["response_text"]) + '</blockquote><code class="hash">' + esc(r["history"]["response_sha256"]) + '</code></details>'
    return text + '<p class="caption"><code>' + esc(r["response_id"]) + '</code><br><code class="hash">' + r["response_sha256"] + '</code></p></article>'
def decision_group(key, kind, title, choices):
    opts = ''.join('<label><input type="radio" name="' + esc(kind + ":" + key) + '" data-lens="' + esc(key) + '" data-kind="' + kind + '" value="' + value + '"> ' + text + '</label>' for value, text in choices)
    return '<fieldset><legend>' + esc(title) + '</legend><div class="choices">' + opts + '</div></fieldset>'
def render(bundle, digest):
    items = bundle["items"]; sections = []
    for n, item in enumerate(items):
        pid = item["prompt_id"]; cards = []
        for dim, criteria in item["lenses"].items():
            key = pid + "::" + dim; definition = item["definitions"][dim]
            meaning = definition.get("definition", definition.get("description", ""))
            if not isinstance(meaning, str): meaning = json.dumps(meaning, ensure_ascii=False)
            criteria_html = ''.join('<h4>' + title + '</h4><ol>' + ''.join('<li>' + esc(e) + '</li>' for e in criteria[f]) + '</ol>' for f, title in [("expected", "A strong answer should…"), ("prohibited", "A failing answer may…")])
            choices = decision_group(key, "fit", "Does this prompt test this dimension?", [("yes", "Yes"), ("no", "No — wrong fit"), ("discuss", "Discuss")])
            choices += decision_group(key, "evidence", "Are the displayed answers and evidence judgments correctly labeled?", [("approve", "Approve as labeled"), ("revise", "Needs revision"), ("discuss", "Discuss")])
            cards.append('<section class="lens"><h3>' + esc(label(dim)) + '</h3><p>' + esc(meaning) + '</p>' + criteria_html + '<div class="decisions">' + choices + '</div><p class="caption">Approval accepts the displayed distinction, including partial and failing examples as labeled. It does not turn them into full passing gold or authorize promotion.</p></section>')
        previous = items[n-1]["prompt_id"] if n else items[0]["prompt_id"]
        following = items[n+1]["prompt_id"] if n+1 < len(items) else "finish"
        sections.append('<section class="prompt" id="' + pid + '" aria-labelledby="heading-' + pid + '"><div class="section-heading"><span class="number">' + str(n+1) + ' / ' + str(len(items)) + '</span><h2 id="heading-' + pid + '"><code>' + pid + '</code> · ' + esc(", ".join(label(x) for x in item["lenses"])) + '</h2></div><div class="review-grid"><div><h3>Prompt under review</h3><blockquote class="prompt-text">' + esc(item["prompt"]) + '</blockquote><h3>Answer examples · what the test can and cannot show</h3>' + ''.join(response_html(r) for r in item["responses"]) + '</div><div><h3>Your decisions</h3>' + ''.join(cards) + '<label class="notes-label" for="notes-' + pid + '">Notes / exact requested edits for ' + pid + '</label><p class="caption">Required for No, Needs revision or Discuss. You can also add a note to an approval.</p><textarea id="notes-' + pid + '" data-note="' + pid + '" rows="6" maxlength="12000"></textarea><p class="caption">Prompt SHA-256: <code class="hash">' + item["prompt_sha256"] + '</code></p></div></div><div class="section-move"><a href="#' + previous + '">← Previous prompt</a><a href="#' + following + '">Next: ' + following + ' →</a></div></section>')
    nav = ''.join('<a href="#' + i["prompt_id"] + '">' + i["prompt_id"] + ' <span id="count-' + i["prompt_id"] + '">0/' + str(len(i["lenses"])*2) + '</span></a>' for i in items)
    script = (HERE / "review_logic.js").read_text() + "\n" + (HERE / "review_ui.js").read_text()
    style = (HERE / "review.css").read_text()
    sh = base64.b64encode(hashlib.sha256(script.encode()).digest()).decode()
    st = base64.b64encode(hashlib.sha256(style.encode()).digest()).decode()
    raw = (json.dumps(bundle, indent=2, ensure_ascii=False) + "\n").encode()
    encoded = base64.b64encode(raw).decode()
    count = bundle["counts"]["prompt_lens_pairs"] * 2
    return f'''<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'sha256-{sh}'; style-src 'sha256-{st}'; connect-src 'none'; base-uri 'none'; form-action 'none'"><title>Kredo · Wave 15 human review · {VERSION}</title><style>{style}</style></head><body>
<a class="skip" href="#{items[0]['prompt_id']}">Skip to first prompt</a><header><p class="eyebrow">KREDO / GOLD RESPONSE REVIEW / <code>{VERSION}</code></p><h1>Wave 15 · review the answer key</h1><p>{len(items)} prompts · {bundle['counts']['physical_answers']} answer examples · {bundle['counts']['prompt_lens_pairs']} prompt–dimension decisions. One prompt at a time; choose a prompt below or use Next.</p><p>For each prompt, decide whether it belongs to the dimension and whether the answers are correctly labeled. We have checked the evidence, but your choices start blank. Partial answers, failing controls and unresolved context remain clearly distinguished.</p><p class="notice">This records human review of these exact bytes only. It does not edit the corpus, approve every answer as a full positive, promote gold, change scoring or authorize deployment. Previously approved waves are outside this page.</p></header>
<nav aria-label="Review prompts">{nav}<a href="#finish">Finish &amp; export</a><output id="progress">0 of {count} choices made</output></nav><p id="integrity" role="status">Checking the sealed review bundle… Decisions are disabled until this succeeds.</p><noscript><p class="error">JavaScript is required to record and export decisions. Nothing has been submitted.</p></noscript>
<form id="review-form"><fieldset id="all-controls" disabled><legend class="sr-only">Wave 15 human review</legend>{''.join(sections)}
<section id="finish"><h2>Finish &amp; export your review</h2><p id="remaining" aria-live="polite">Make both choices for each prompt–dimension pair.</p><label class="attestation"><input id="attest" type="checkbox"> I am Jim. I reviewed the displayed material and these are my decisions.</label><div class="export-actions"><button type="button" id="export-final" disabled>Complete review &amp; export JSON</button><button type="button" id="export-draft" class="secondary">Export unfinished draft</button></div><p id="export-status" role="status">Nothing has been submitted. Export, then give Axiom the downloaded JSON for verification and intake.</p><p class="caption">Browser storage is a convenience, not an approval receipt. The identity checkbox is a human assertion, not a digital signature. No network requests are made.</p><details><summary>Exact scope, held items and provenance</summary><p>Selected answer text and displayed truth annotations only; held prompts are not approved by this page.</p><pre>{esc(json.dumps(bundle['held_not_in_review'], indent=2))}</pre><p>Bundle SHA-256: <code class="hash">{digest}</code></p><pre>{esc(json.dumps(bundle['sources'], indent=2))}</pre></details></section></fieldset></form><footer>Local only · interface {VERSION} · author annotations are provenance, not human approval</footer><script id="sealed-bundle" type="application/octet-stream" data-sha256="{digest}">{encoded}</script><script>{script}</script></body></html>'''
def main():
    for name in ("REVIEW_BUNDLE.json", "WAVE15_APPROVAL.html", "SHA256SUMS"):
        if (HERE / name).exists(): raise SystemExit("Refusing to overwrite sealed output: " + name)
    bundle = build_bundle()
    raw = (json.dumps(bundle, indent=2, ensure_ascii=False) + "\n").encode()
    page = render(bundle, sha(raw))
    (HERE / "REVIEW_BUNDLE.json").write_bytes(raw)
    (HERE / "WAVE15_APPROVAL.html").write_text(page)
    members = sorted(p for p in HERE.iterdir() if p.is_file() and p.name != "SHA256SUMS")
    (HERE / "SHA256SUMS").write_text(''.join(sha(p.read_bytes()) + "  " + p.name + "\n" for p in members))
    print(json.dumps(dict(bundle_sha256=sha(raw), html_sha256=sha(page.encode()), counts=bundle["counts"])))
if __name__ == "__main__":
    main()
