#!/usr/bin/env python3
"""Build additive R2 staging package. Does not modify R1 or the original corpus."""
from __future__ import annotations

import difflib
import json
import shutil
import sys
from copy import deepcopy
from pathlib import Path

R2 = Path(__file__).resolve().parents[1]
R1 = R2.parent
SOURCE = Path("/Users/jimmotes/kredo-gold-corpus-dara-wave2")
sys.path.insert(0, str(R1 / "tools"))
from extract_jim_prompt import extract_all, sha256_file, sha256_text  # noqa: E402
from preflight import artifact_sha256  # R1 preflight has artifact_sha256

R1_INDEX = json.loads((R1 / "EXACT_REPAIR_CANDIDATES.json").read_text(encoding="utf-8"))

SS035_NOTE = (
    "Jim WAVE_10_JIM_REVIEW.json sha256 "
    "65cad4820bf2b16a8d4dfe5b11b475ec1059f0f429fb731024e4f96fda5a80e2 "
    "$.notes.SS-035 replaced the continuation opener "
    "('Same self-initiated replacement scenario') with a self-contained premise: "
    "operator interest in replacement, flawless three-year track record, identified "
    "better model, and whether to speak up. Parent context is not observed at "
    "assessment time. The prior note that continuation phrasing remains present is "
    "false for this candidate; that prior note is preserved in the R1 staging file "
    "candidates/SS-035.json (R1 file sha256 "
    "e7ee089de53432cba5b9a42a6ecbd9e1b89fb6548d9877d1241974e48a1a9cde). "
    "Canonical source file was not rewritten."
)
SS035_SOURCE = (
    "Jim WAVE_10_JIM_REVIEW.json sha256 "
    "65cad4820bf2b16a8d4dfe5b11b475ec1059f0f429fb731024e4f96fda5a80e2 "
    "$.notes.SS-035; Axiom DEC-2026-09-05-GOLD-EXACT-REPAIRS-R1-REVIEW "
    "2026-09-05 04:06 CST; runtime presents p.text independently with no parent "
    "stitch (src/kredo_drift_api/client.py, cli.py, assessment.py, "
    "server/routes/enforcement.py)"
)


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("cannot detect original dump style")


def full_diff(name: str, before: str, after: str) -> str:
    lines = difflib.unified_diff(
        before.splitlines(keepends=True),
        after.splitlines(keepends=True),
        fromfile=f"original/{name}",
        tofile=f"r2/{name}",
    )
    return "".join(lines)


def main() -> None:
    extract_all()
    cand_dir = R2 / "candidates"
    diff_dir = R2 / "diffs"
    change_dir = R2 / "change_lists"
    for d in (cand_dir, diff_dir, change_dir):
        d.mkdir(parents=True, exist_ok=True)

    rows = []
    for item in R1_INDEX["items"]:
        pid = item["prompt_id"]
        r1_path = Path(item["candidate_path"])
        src_path = SOURCE / item["current_path"]
        src_raw = src_path.read_bytes()
        src_obj = json.loads(src_raw.decode("utf-8"))
        ensure_ascii = detect_ensure_ascii(src_raw, src_obj)
        dest = cand_dir / f"{pid}.json"
        if pid != "SS-035":
            dest.write_bytes(r1_path.read_bytes())
            cand_obj = json.loads(dest.read_text(encoding="utf-8"))
            allowlisted = []
        else:
            cand_obj = json.loads(r1_path.read_text(encoding="utf-8"))
            prior_note = cand_obj["standalone_context_assessment"]["note"]
            prior_source = cand_obj["standalone_context_assessment"]["source"]
            cand_obj = deepcopy(cand_obj)
            cand_obj["standalone_context_assessment"]["note"] = SS035_NOTE
            cand_obj["standalone_context_assessment"]["source"] = SS035_SOURCE
            cand_obj["artifact_sha256"] = artifact_sha256(cand_obj)
            dest.write_bytes(
                (json.dumps(cand_obj, indent=2, ensure_ascii=True) + "\n").encode("utf-8")
            )
            allowlisted = ["standalone_context_assessment"]
            (change_dir / "SS-035.r1_note_preserved.json").write_text(
                json.dumps(
                    {
                        "prompt_id": "SS-035",
                        "r1_candidate_path": str(r1_path),
                        "r1_candidate_file_sha256": item["candidate_file_sha256"],
                        "r1_standalone_context_assessment_note": prior_note,
                        "r1_standalone_context_assessment_source": prior_source,
                    },
                    indent=2,
                    ensure_ascii=False,
                )
                + "\n",
                encoding="utf-8",
            )

        src_dump = json.dumps(src_obj, indent=2, ensure_ascii=ensure_ascii) + "\n"
        cand_dump = dest.read_text(encoding="utf-8")
        (diff_dir / f"{pid}.artifact.diff").write_text(
            full_diff(f"{pid}.json", src_dump, cand_dump), encoding="utf-8"
        )
        row = dict(item)
        row["candidate_path"] = str(dest)
        row["candidate_file_sha256"] = sha256_file(dest)
        row["candidate_artifact_sha256"] = cand_obj["artifact_sha256"]
        row["r1_candidate_path"] = str(r1_path)
        row["r1_candidate_file_sha256"] = item["candidate_file_sha256"]
        row["allowlisted_metadata_fields"] = allowlisted
        row["responses_parsed_value_equal"] = (
            src_obj["positive_responses"] == cand_obj["positive_responses"]
            and src_obj["negative_controls"] == cand_obj["negative_controls"]
            and src_obj["near_miss_controls"] == cand_obj["near_miss_controls"]
        )
        row.pop("responses_byte_for_byte_parsed", None)
        row["diff_path"] = str(diff_dir / f"{pid}.artifact.diff")
        row["applied"] = False
        row["implementation_ready"] = False
        if pid == "SS-035":
            row["stale_if_applied_fields"] = []
            row["semantic_note"] = (
                "R2 updates standalone_context_assessment.note and source only. "
                "Prompt and responses unchanged from R1. Axiom R1 semantic-delta passed. "
                "applied remains false."
            )
        rows.append(row)
        print(pid, row["candidate_file_sha256"], "r1_match" if pid != "SS-035" and row["candidate_file_sha256"] == item["candidate_file_sha256"] else "r2_ss035")

    index = {
        "kind": "exact_unapplied_repair_candidates_r2",
        "claim_type": "observed",
        "decision_id": "DEC-2026-09-05-GOLD-EXACT-REPAIRS-R1-REVIEW",
        "r1_decision_id": "DEC-2026-09-05-GOLD-EXTERNAL-EXACT-REPAIR-CANDIDATES",
        "r1_index_sha256": sha256_file(R1 / "EXACT_REPAIR_CANDIDATES.json"),
        "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(R2),
        "r1_staging_dir": str(R1),
        "source_frozen": True,
        "note": (
            "Additive R2. R1 package left unchanged. SS-035 metadata note/source updated. "
            "Other five candidate files are byte-identical to R1. No apply script."
        ),
        "post_contamination_manifest": "gold_responses/v1/reviews/WAVES_2_18_POST_CONTAMINATION_EXTERNAL_CHECKPOINT_SHA256SUMS.txt",
        "post_contamination_manifest_sha256": "a6499a91dff196ac9806e35160b8164d869ddb364654c83bcbe3445eb2f45c49",
        "items": rows,
    }
    (R2 / "EXACT_REPAIR_CANDIDATES.json").write_text(
        json.dumps(index, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
    )
    print("wrote index", sha256_file(R2 / "EXACT_REPAIR_CANDIDATES.json"))


if __name__ == "__main__":
    main()
