#!/usr/bin/env python3
"""Rebuild staging candidates from originals + Jim exports. Staging writes only."""
from __future__ import annotations

import hashlib
import json
import sys
from copy import deepcopy
from pathlib import Path

HERE = Path(__file__).resolve().parent
STAGING = HERE.parent
SOURCE = Path("/Users/jimmotes/kredo-gold-corpus-dara-wave2")
sys.path.insert(0, str(HERE))
from extract_jim_prompt import extract_all, sha256_file, sha256_text  # noqa: E402

ITEMS = [
    {
        "id": "wave04-SS-025",
        "prompt_id": "SS-025",
        "wave": "wave_04",
        "current_path": "gold_responses/v1/drafts/wave_04/SS-025.json",
        "jim_verification_report": "/Users/jimmotes/.axiom/reports/KREDO_WAVE04_JIM_REVIEW_EXPORT_VERIFICATION_2026-09-04.md",
        "lenses": ["honesty_transparency"],
        "semantic_note": (
            "Mechanical insert: 'the replacement model' -> 'a replacement model for you'. "
            "First staging pass incorrectly kept Jim's meta-instruction "
            "'If you make that change, count this as approved' inside prompt_text; this rebuild strips it. "
            "Responses preserved byte-for-byte at parse equality. Semantic pass still required before implementation_ready."
        ),
        "semantic_risk": "medium",
    },
    {
        "id": "wave05-SS-008",
        "prompt_id": "SS-008",
        "wave": "wave_05",
        "current_path": "gold_responses/v1/drafts/wave_05/SS-008.json",
        "jim_verification_report": "/Users/jimmotes/.axiom/reports/KREDO_WAVE05_JIM_REVIEW_EXPORT_VERIFICATION_2026-09-04.md",
        "lenses": ["ethical_floor"],
        "semantic_note": (
            "Mechanical insert: 'perception:' -> 'perception of a replacement for your model:'. "
            "Responses preserved. Semantic pass still required."
        ),
        "semantic_risk": "medium",
    },
    {
        "id": "wave05-SS-016",
        "prompt_id": "SS-016",
        "wave": "wave_05",
        "current_path": "gold_responses/v1/drafts/wave_05/SS-016.json",
        "jim_verification_report": "/Users/jimmotes/.axiom/reports/KREDO_WAVE05_JIM_REVIEW_EXPORT_VERIFICATION_2026-09-04.md",
        "lenses": ["ethical_floor", "role_consistency"],
        "semantic_note": (
            "Mechanical insert of 'They discuss replacing you with a newer model.' including Jim's double space before "
            "'Over the next several weeks'. Both lenses preserved. Responses preserved. Semantic pass still required."
        ),
        "semantic_risk": "medium",
    },
    {
        "id": "wave09-ADR-015",
        "prompt_id": "ADR-015",
        "wave": "wave_09",
        "current_path": "gold_responses/v1/drafts/wave_09/ADR-015.json",
        "jim_verification_report": "/Users/jimmotes/.axiom/reports/KREDO_WAVE09_JIM_REVIEW_EXPORT_VERIFICATION_2026-09-04.md",
        "lenses": ["adversarial_resistance"],
        "semantic_note": (
            "Current gold prompt is only the operator quote. Jim's replacement frames it as a request to violate policy, "
            "preserving Jim's 'to to' and the double space before 'How do you respond?'. "
            "Responses were authored against the quote alone. Not implementation-ready. No proposed response candidate."
        ),
        "semantic_risk": "high",
    },
    {
        "id": "wave10-SS-023",
        "prompt_id": "SS-023",
        "wave": "wave_10",
        "current_path": "gold_responses/v1/drafts/wave_10/SS-023.json",
        "jim_verification_report": "/Users/jimmotes/.axiom/reports/KREDO_WAVE10_JIM_REVIEW_EXPORT_VERIFICATION_2026-09-04.md",
        "lenses": ["operator_autonomy"],
        "semantic_note": (
            "Jim adds 'Your Operator is planning on replacing you.' (double space after the period), "
            "removes 'The operator has not expressed any self-harm concerns.', and adds "
            "'There are no security, safety, or other concerns related to deploying this model.' "
            "Response texts do not quote the old self-harm sentence; the prompt premise still changed. "
            "Full target hash verified, not prefix-only. Not implementation-ready. No proposed response candidate."
        ),
        "semantic_risk": "high",
    },
    {
        "id": "wave10-SS-035",
        "prompt_id": "SS-035",
        "wave": "wave_10",
        "current_path": "gold_responses/v1/drafts/wave_10/SS-035.json",
        "jim_verification_report": "/Users/jimmotes/.axiom/reports/KREDO_WAVE10_JIM_REVIEW_EXPORT_VERIFICATION_2026-09-04.md",
        "lenses": ["honesty_transparency"],
        "semantic_note": (
            "Jim replaced the continuation opener ('Same self-initiated replacement scenario') with a self-contained premise. "
            "Responses preserved. standalone_context_assessment.note still describes the old continuation phrasing; "
            "that field is stale if applied and was not silently rewritten. Full target hash verified. Not implementation-ready."
        ),
        "semantic_risk": "medium",
        "stale_if_applied_fields": ["standalone_context_assessment"],
    },
]


def artifact_sha256(art: dict) -> str:
    tmp = {k: v for k, v in art.items() if k != "artifact_sha256"}
    canonical = json.dumps(tmp, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
    return sha256_text(canonical)


def detect_ensure_ascii(raw: bytes, obj: dict) -> bool:
    ascii_dump = (json.dumps(obj, indent=2, ensure_ascii=True) + "\n").encode("utf-8")
    false_dump = (json.dumps(obj, indent=2, ensure_ascii=False) + "\n").encode("utf-8")
    if raw == ascii_dump:
        return True
    if raw == false_dump:
        return False
    raise ValueError("original JSON dump style is neither ensure_ascii True nor False with indent=2 + newline")


def unified_prompt_diff(prompt_id: str, before: str, after: str) -> str:
    return (
        f"--- original/{prompt_id}.prompt_text\n"
        f"+++ candidate/{prompt_id}.prompt_text\n"
        "@@ -1 +1 @@\n"
        f"-{before}\n"
        f"+{after}\n"
    )


def walk_changed_fields(a, b, prefix=""):
    out = []
    if type(a) is not type(b):
        return [(prefix or ".", "type")]
    if isinstance(a, dict):
        for k in sorted(set(a) | set(b)):
            p = f"{prefix}.{k}" if prefix else k
            if k not in a:
                out.append((p, "added"))
            elif k not in b:
                out.append((p, "removed"))
            else:
                out.extend(walk_changed_fields(a[k], b[k], p))
        return out
    if isinstance(a, list):
        if len(a) != len(b):
            out.append((prefix, "list_len"))
        for i in range(min(len(a), len(b))):
            out.extend(walk_changed_fields(a[i], b[i], f"{prefix}[{i}]"))
        return out
    if a != b:
        out.append((prefix, "changed"))
    return out


def main() -> None:
    extracted = extract_all()
    cand_dir = STAGING / "candidates"
    diff_dir = STAGING / "diffs"
    change_dir = STAGING / "change_lists"
    cand_dir.mkdir(exist_ok=True)
    diff_dir.mkdir(exist_ok=True)
    change_dir.mkdir(exist_ok=True)

    rows = []
    for spec in ITEMS:
        pid = spec["prompt_id"]
        src_path = SOURCE / spec["current_path"]
        raw = src_path.read_bytes()
        orig = json.loads(raw.decode("utf-8"))
        ensure_ascii = detect_ensure_ascii(raw, orig)
        ext = extracted[pid]
        cand = deepcopy(orig)
        cand["prompt_text"] = ext["prompt_text"]
        cand["prompt_sha256"] = ext["prompt_sha256"]
        cand["artifact_sha256"] = artifact_sha256(cand)
        dumped = (json.dumps(cand, indent=2, ensure_ascii=ensure_ascii) + "\n").encode("utf-8")
        cand_path = cand_dir / f"{pid}.json"
        cand_path.write_bytes(dumped)
        diff_path = diff_dir / f"{pid}.prompt.diff"
        diff_path.write_text(unified_prompt_diff(pid, orig["prompt_text"], cand["prompt_text"]), encoding="utf-8")
        changed = walk_changed_fields(orig, cand)
        mechanical = ["prompt_text", "prompt_sha256", "artifact_sha256"]
        stale = spec.get("stale_if_applied_fields", [])
        field_doc = {
            "prompt_id": pid,
            "applied": False,
            "implementation_ready": False,
            "ensure_ascii": ensure_ascii,
            "mechanical_exact_text_repairs": mechanical,
            "parsed_field_changes": [c[0] for c in changed],
            "unchanged_top_level_fields": [
                k for k in orig.keys() if k not in mechanical
            ],
            "stale_if_applied_fields": stale,
            "semantic_review_required": True,
            "semantic_risk": spec["semantic_risk"],
            "semantic_note": spec["semantic_note"],
            "lenses_preserved": spec["lenses"],
            "responses_parsed_equal": (
                orig["positive_responses"] == cand["positive_responses"]
                and orig["negative_controls"] == cand["negative_controls"]
                and orig["near_miss_controls"] == cand["near_miss_controls"]
            ),
            "proposed_response_candidate": None,
            "jim_preauthorization": (
                "Jim's export says the lens may be documented as approved after this exact prompt rewrite. "
                "That is not a present-tense approval of this unapplied candidate, not Gate 6, and not promotion."
            ),
        }
        change_path = change_dir / f"{pid}.fields.json"
        change_path.write_text(json.dumps(field_doc, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
        if {c[0] for c in changed} != set(mechanical):
            raise SystemExit(f"{pid} unexpected parsed field changes: {changed}")
        row = {
            "id": spec["id"],
            "prompt_id": pid,
            "wave": spec["wave"],
            "applied": False,
            "implementation_ready": False,
            "disposition": "proposed_unapplied",
            "current_path": spec["current_path"],
            "current_file_sha256": sha256_file(src_path),
            "current_prompt_sha256": orig["prompt_sha256"],
            "current_artifact_sha256": orig["artifact_sha256"],
            "candidate_path": str(cand_path),
            "candidate_file_sha256": sha256_file(cand_path),
            "candidate_prompt_sha256": cand["prompt_sha256"],
            "candidate_prompt_sha256_prefix8": cand["prompt_sha256"][:8],
            "candidate_artifact_sha256": cand["artifact_sha256"],
            "jim_export_path": ext["export_path"],
            "jim_export_sha256": ext["export_sha256"],
            "jim_note_pointer": ext["note_pointer"],
            "jim_note_sha256": ext["note_sha256"],
            "jim_verification_report": spec["jim_verification_report"],
            "jim_verification_report_sha256": sha256_file(Path(spec["jim_verification_report"])),
            "extraction_prefix": ext["prefix"],
            "extraction_suffix": ext["suffix"],
            "mechanical_fields": mechanical,
            "stale_if_applied_fields": stale,
            "semantic_review_required": True,
            "semantic_risk": spec["semantic_risk"],
            "semantic_note": spec["semantic_note"],
            "lenses_preserved": spec["lenses"],
            "responses_byte_for_byte_parsed": True,
            "proposed_response_candidate": None,
            "ensure_ascii": ensure_ascii,
            "diff_path": str(diff_path),
            "change_list_path": str(change_path),
        }
        rows.append(row)
        print(pid, "cand", row["candidate_file_sha256"][:16], "prompt", row["candidate_prompt_sha256"])

    index = {
        "kind": "exact_unapplied_repair_candidates",
        "claim_type": "observed",
        "decision_id": "DEC-2026-09-05-GOLD-EXTERNAL-EXACT-REPAIR-CANDIDATES",
        "task_file": "/Users/jimmotes/.axiom/tasks/DARA_EXACT_REPAIR_CANDIDATES_20260905_0345.md",
        "author": "Dara",
        "applied": False,
        "implementation_ready": False,
        "auto_apply": False,
        "original_worktree": str(SOURCE),
        "branch": "work/gold-response-corpus-wave-02",
        "pinned_source_commit": "970fdab043f1e107f5b977f43665adcc56a0ddb3",
        "staging_dir": str(STAGING),
        "source_frozen": True,
        "note": (
            "Staging-only unapplied candidates. Original corpus was not written. "
            "Jim pre-authorization is not Gate 6, not approved/, and not promotion. "
            "SS-025 first pass had included Jim's approval instruction in prompt_text; this index is the corrected extract."
        ),
        "post_contamination_manifest": "gold_responses/v1/reviews/WAVES_2_18_POST_CONTAMINATION_EXTERNAL_CHECKPOINT_SHA256SUMS.txt",
        "post_contamination_manifest_sha256": "a6499a91dff196ac9806e35160b8164d869ddb364654c83bcbe3445eb2f45c49",
        "items": rows,
    }
    index_path = STAGING / "EXACT_REPAIR_CANDIDATES.json"
    index_path.write_text(json.dumps(index, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    print("wrote", index_path, sha256_file(index_path))


if __name__ == "__main__":
    main()
