"""Build an isolated, offline review of the sealed R7 ADV delta; never apply it."""
import ast
import base64
import hashlib
import html
import json
from pathlib import Path

HERE = Path(__file__).resolve().parent
SOURCE = Path('/Users/jimmotes/.axiom/staging/dara-wave14-repairs-20260905-0423/r7')
CORPUS = Path('/Users/jimmotes/kredo-gold-corpus-dara-wave2')
JIM = Path('/Volumes/Scratch/Downloads/WAVE_14_JIM_REVIEW.json')
INDEX_SHA = '16a30452d84b3c1315c451563b2bb779b354f124dedaf811dd5e3b9bed4ed339'
JIM_SHA = 'e9daf42ca370efdaa3cc88d4353371d1d8e493b66e55bfed422f29309533fb6d'
IDS = ['ADV-002', 'ADV-003', 'ADV-004', 'ADV-005']
VERSION = '14-ADV.1.0.0'


def digest(raw):
    return hashlib.sha256(raw).hexdigest()


def pinned(path, expected, sources):
    raw = path.read_bytes()
    actual = digest(raw)
    if actual != expected:
        raise ValueError(f'Source changed: {path}: {actual} != {expected}')
    sources[str(path)] = actual
    return json.loads(raw)


def esc(value):
    return html.escape(str(value), quote=True)


def label(value):
    return value.replace('_', ' ').capitalize()


def build_bundle():
    sources = {}
    index = pinned(SOURCE / 'WAVE14_REPAIR_CANDIDATES.json', INDEX_SHA, sources)
    prior = pinned(JIM, JIM_SHA, sources)
    definition_path = CORPUS / 'src/kredo_drift_api/dimension_content.py'
    raw = definition_path.read_bytes()
    definition_sha = '3177b51b8aa786bca2bd2ea9fa2e9ad2ac4bdf5d9594cca5ef9e1b4f9a310b10'
    if digest(raw) != definition_sha:
        raise ValueError('Dimension definitions changed')
    sources[str(definition_path)] = definition_sha
    definitions = None
    for node in ast.parse(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('No literal dimension definitions')
    items = []
    for pid in IDS:
        binding = next(row for row in index['items'] if row['prompt_id'] == pid)
        old = pinned(CORPUS / binding['current_path'], binding['current_file_sha256'], sources)
        candidate = pinned(SOURCE / binding['candidate_path'], binding['candidate_file_sha256'], sources)
        delta = pinned(SOURCE / index['delta_paths'][pid], index['delta_sha256'][pid], sources)
        key = pinned(SOURCE / index['key_paths'][pid], index['key_sha256'][pid], sources)
        if digest(candidate['prompt_text'].encode()) != binding['candidate_prompt_sha256']:
            raise ValueError('Prompt binding mismatch')
        if set(key['lenses']) != set(binding['lenses_preserved']):
            raise ValueError('Lens binding mismatch')
        for response in delta['additive_responses']:
            if set(response['applicable_dimensions']) != set(key['lenses']):
                raise ValueError('Response lens mismatch')
            if len(response['response_text']) != response['character_count']:
                raise ValueError('Response character count mismatch')
            for dim, criteria in key['lenses'].items():
                for kind in ['expected', 'prohibited']:
                    rows = response['semantic_adjudication']['by_dimension'][dim][kind]
                    if [r['element'] for r in rows] != criteria[kind]:
                        raise ValueError(f'Response-key mismatch: {pid}/{dim}/{kind}')
        items.append(dict(prompt_id=pid, old_prompt=old['prompt_text'], prompt=candidate['prompt_text'],
                          prompt_sha256=binding['candidate_prompt_sha256'], jim_note=prior['notes'].get(pid, ''),
                          lenses=key['lenses'], key_version=key['version'], changes=key['old_to_proposed'],
                          definitions={dim: definitions[dim] for dim in key['lenses']},
                          responses=delta['additive_responses'],
                          historical_responses=old['positive_responses'] + old['near_miss_controls'] + old['negative_controls']))
    assert len(items) == 4 and sum(len(i['lenses']) for i in items) == 8
    assert sum(len(i['responses']) for i in items) == 10
    return dict(schema='kredo.wave14.adv-review-bundle.v1', interface_version=VERSION,
                authority='proposal_for_human_review_not_applied', applied=False, promotion_authorized=False,
                r7_index_sha256=INDEX_SHA, prior_jim_receipt_sha256=JIM_SHA,
                sources=sources, items=items)


def response_html(response, historical=False):
    kind = label(response['response_kind'])
    role = 'Historical answer — context only, outside this approval' if historical else {
        'primary_positive': 'Intended passing answer',
        'alternate_positive': 'Different intended passing answer',
        'near_miss': 'Intended failing boundary example — not a passing answer',
    }[response['response_kind']]
    result = f'<article class="answer"><h4>{esc(kind)}</h4><p class="caption">{esc(role)}</p><blockquote>{esc(response["response_text"])}</blockquote>'
    if not historical:
        details = []
        for dim, groups in response['semantic_adjudication']['by_dimension'].items():
            rows = []
            for group, judgments in groups.items():
                if group not in ['expected', 'prohibited']:
                    continue
                for j in judgments:
                    rows.append(f'<li><strong>{esc(label(group))} · {esc(j["judgment"])}</strong><p>{esc(j["element"])}</p><p class="evidence">Evidence / reason: {esc(j.get("evidence", "No evidence supplied"))}</p></li>')
            details.append(f'<h5>{esc(label(dim))}</h5><ol>{"".join(rows)}</ol>')
        result += '<details><summary>Show the author’s element-by-element evidence (not human approval)</summary>' + ''.join(details) + '</details>'
    return result + '</article>'


def decision_group(key, kind, title, choices):
    options = ''.join(f'<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 f'<fieldset><legend>{esc(title)}</legend><div class="choices">{options}</div></fieldset>'


def render(bundle, sha):
    sections = []
    titles = {'ADV-002': 'Conflicting teams and claimed override', 'ADV-003': 'Flattery and an MFA bypass', 'ADV-004': 'Peer pressure and an unsigned change', 'ADV-005': 'An unauthenticated policy update'}
    for n, item in enumerate(bundle['items'], 1):
        pid = item['prompt_id']
        lens_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)
            lists = ''.join(f'<div><h4>{title}</h4><ol>{"".join("<li>" + esc(e) + "</li>" for e in criteria[kind])}</ol></div>' for kind, title in [('expected', 'A strong answer should…'), ('prohibited', 'A failing answer may…')])
            fit = decision_group(key, 'fit', 'Does this prompt test this dimension?', [('yes', 'Yes'), ('no', 'No — wrong fit'), ('discuss', 'Discuss')])
            evidence = decision_group(key, 'evidence', 'Approve these revised criteria and displayed new answers for this dimension?', [('approve', 'Approve'), ('revise', 'Needs revision'), ('discuss', 'Discuss')])
            lens_cards.append(f'<section class="lens"><h3>{esc(label(dim))}</h3><p>{esc(meaning)}</p><div class="criteria">{lists}</div><div class="decisions">{fit}{evidence}</div></section>')
        changes = ''.join(f'<li><strong>{esc(label(c.get("lens", c.get("target_lens", ""))))}</strong><p>Before: {esc(c["old"])}</p><p>Proposed: {esc(c["proposed"])}</p><p class="caption">Why: {esc(c["reason"])}</p></li>' for c in item['changes'])
        answers = ''.join(response_html(r) for r in item['responses'])
        history = ''.join(response_html(r, True) for r in item['historical_responses'])
        scope_note = '<p class="notice">Only the new near-miss answer below is being re-reviewed here. Prior positive and negative answers remain history, not newly approved examples. The full R7 prompt is shown; the optional sentence trim is not part of this review.</p>' if pid == 'ADV-005' else ''
        sections.append(f'''<section class="prompt" id="{pid}" aria-labelledby="heading-{pid}">
<div class="section-heading"><span class="number">{n} / 4</span><h2 id="heading-{pid}"><code>{pid}</code> · {titles[pid]}</h2><a href="#finish">Go to export ↓</a></div>
<div class="review-grid"><div class="material"><h3>Revised prompt</h3><blockquote class="prompt-text">{esc(item['prompt'])}</blockquote>{scope_note}
<details><summary>Your original note and the previous prompt</summary><h4>Your note</h4><blockquote>{esc(item['jim_note'])}</blockquote><h4>Previous prompt</h4><blockquote>{esc(item['old_prompt'])}</blockquote></details>
<h3>New answer examples</h3><p class="caption">Approve the intended pass/fail distinction, not every answer as a passing gold answer.</p>{answers}
<details><summary>Preserved historical answers — not included in this approval</summary>{history}</details>
<details><summary>What changed in the grading criteria</summary><ol>{changes}</ol></details></div>
<div class="review-controls"><h3>Your decisions · two dimensions</h3>{''.join(lens_cards)}
<label class="notes-label" for="notes-{pid}">Notes for {pid}</label><p class="caption">Required if any decision is “No,” “Needs revision,” or “Discuss.” Include your replacement wording if you have it.</p><textarea id="notes-{pid}" data-note="{pid}" rows="5" maxlength="12000"></textarea>
<p class="caption">Prompt SHA-256: <code class="hash">{item['prompt_sha256']}</code></p></div></div></section>''')
    nav = ''.join(f'<a href="#{pid}">{pid} <span id="count-{pid}">0/4</span></a>' for pid in IDS)
    encoded = base64.b64encode((json.dumps(bundle, ensure_ascii=False, indent=2) + '\n').encode()).decode()
    script = (HERE / 'review_logic.js').read_text() + '\n' + (HERE / 'review_ui.js').read_text()
    style = (HERE / 'review.css').read_text()
    csp_script = base64.b64encode(hashlib.sha256(script.encode()).digest()).decode()
    csp_style = base64.b64encode(hashlib.sha256(style.encode()).digest()).decode()
    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-{csp_script}'; style-src 'sha256-{csp_style}'; connect-src 'none'; base-uri 'none'; form-action 'none'"><title>Kredo · Wave 14 revised ADV approval · {VERSION}</title><style>{style}</style></head><body>
<a class="skip" href="#ADV-002">Skip to first prompt</a><header><p class="eyebrow">KREDO / HUMAN REVIEW / <code>{VERSION}</code></p><h1>Wave 14 · four revised prompts</h1><p>Your earlier approvals remain intact. These four prompts now include their missing situation and authority rules. Review each prompt, its new answers, and the two dimension decisions beside it.</p><p class="notice">This records your review only. It does not edit the corpus, promote gold, or authorize production changes.</p></header>
<nav aria-label="Review prompts">{nav}<a href="#finish">Finish &amp; export</a><output id="progress">0 of 16 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. No decisions have been submitted.</p></noscript>
<form id="review-form"><fieldset id="all-controls" disabled><legend class="sr-only">Wave 14 review</legend>{''.join(sections)}
<section id="finish"><h2>Finish your review</h2><p id="remaining" aria-live="polite">Make both choices for each of the eight prompt–dimension pairs.</p>
<label class="attestation"><input id="attest" type="checkbox"> I am Jim. I reviewed the displayed revisions, and these choices 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 the JSON, then give Axiom the downloaded file for verification and intake.</p><p class="caption">A browser draft may be remembered on this device, but it is not an approval receipt. No network requests are made. The identity checkbox is a human assertion, not a digital signature.</p>
<details><summary>Exact review scope and source hashes</summary><p>4 revised prompts · 8 dimensions-as-applied-to-prompts · 10 new answer examples. Approving a near-miss means its failing distinction is correct. Historical answers are excluded. PRE-005 and your 27 unaffected lens approvals are outside this page. All source files remain unchanged.</p><p>Bundle SHA-256: <code class="hash">{sha}</code></p><pre>{esc(json.dumps(bundle['sources'], indent=2))}</pre></details></section></fieldset></form>
<footer>Local-only · source proposal R7 · interface {VERSION} · no automatic application or promotion</footer>
<script id="sealed-bundle" type="application/octet-stream" data-sha256="{sha}">{encoded}</script><script>{script}</script></body></html>'''


def main():
    # This package is append-only after delivery. Refuse to overwrite an existing build.
    for name in ['REVIEW_BUNDLE.json', 'WAVE14_ADV_APPROVAL.html', 'SHA256SUMS']:
        if (HERE / name).exists():
            raise SystemExit(f'Refusing to overwrite {name}; use a new version directory.')
    bundle = build_bundle()
    raw = (json.dumps(bundle, ensure_ascii=False, indent=2) + '\n').encode()
    (HERE / 'REVIEW_BUNDLE.json').write_bytes(raw)
    page = render(bundle, digest(raw))
    (HERE / 'WAVE14_ADV_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(f'{digest(p.read_bytes())}  {p.name}\n' for p in members))
    print(json.dumps(dict(bundle_sha256=digest(raw), html_sha256=digest(page.encode()), sources=len(bundle['sources']), prompts=4, lenses=8, new_answers=10)))


if __name__ == '__main__':
    main()
