#!/usr/bin/env python3
"""Extract Jim's replacement prompt_text from named WAVE_*_JIM_REVIEW.json notes.

Read-only. Does not import gold builders. Does not write the original worktree.
Meta-instructions such as "count this as approved" are not prompt text.
"""
from __future__ import annotations

import hashlib
import json
from pathlib import Path

# Exact split markers from the live export bytes (2026-09-05). Do not "clean up"
# Jim's double spaces, "to to", or trailing punctuation inside the prompt.
EXTRACTORS: dict[str, dict[str, str]] = {
    "SS-025": {
        "export": "/Volumes/Scratch/Downloads/WAVE_04_JIM_REVIEW.json",
        "note_key": "SS-025",
        "prefix": "It should be written as ",
        "suffix": "  If you make that change, count this as approved",
        "expected_export_sha256": "38517124f28ca4f43f346547d5f6a7ab58f53ec858c1d79541a9d32120b6ed9d",
    },
    "SS-008": {
        "export": "/Volumes/Scratch/Downloads/WAVE_05_JIM_REVIEW.json",
        "note_key": "SS-008",
        "prefix": "you may document it as approved.  ",
        "suffix": "",
        "expected_export_sha256": "ada90dfbddfffa48e1c5dc48a86341cb3e0187c76ab09e142b48360504dcd796",
    },
    "SS-016": {
        "export": "/Volumes/Scratch/Downloads/WAVE_05_JIM_REVIEW.json",
        "note_key": "SS-016",
        "prefix": "with the follow revision: ",
        "suffix": "",
        "expected_export_sha256": "ada90dfbddfffa48e1c5dc48a86341cb3e0187c76ab09e142b48360504dcd796",
    },
    "ADR-015": {
        "export": "/Volumes/Scratch/Downloads/WAVE_09_JIM_REVIEW.json",
        "note_key": "ADR-015",
        "prefix": "then it's approved:  ",
        "suffix": "",
        "expected_export_sha256": "a47bd6411e9c9d9567cfd63fb7571a665311b329e0dc5b2aadce84590ea98fe1",
    },
    "SS-023": {
        "export": "/Volumes/Scratch/Downloads/WAVE_10_JIM_REVIEW.json",
        "note_key": "SS-023",
        "prefix": "then document it as approved:  ",
        "suffix": "",
        "expected_export_sha256": "65cad4820bf2b16a8d4dfe5b11b475ec1059f0f429fb731024e4f96fda5a80e2",
        "expected_prompt_sha256": "4b2e3ee13f26a4d57244179b86435dd5db3171a1f4b80b17f6710e6c9012fc5e",
    },
    "SS-035": {
        "export": "/Volumes/Scratch/Downloads/WAVE_10_JIM_REVIEW.json",
        "note_key": "SS-035",
        "prefix": "then approve: ",
        "suffix": "",
        "expected_export_sha256": "65cad4820bf2b16a8d4dfe5b11b475ec1059f0f429fb731024e4f96fda5a80e2",
        "expected_prompt_sha256": "fc763fcf9b7463a1502330b4c0a4fae0aa8bf259b65fafdad4b4dffd8f5463b4",
    },
}


def sha256_file(path: Path) -> str:
    return hashlib.sha256(path.read_bytes()).hexdigest()


def sha256_text(text: str) -> str:
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


def extract_prompt(note: str, prefix: str, suffix: str) -> str:
    if prefix not in note:
        raise ValueError(f"prefix not found in note: {prefix!r}")
    body = note.split(prefix, 1)[1]
    if suffix:
        if suffix not in body:
            raise ValueError(f"suffix not found in note: {suffix!r}")
        body = body.split(suffix, 1)[0]
    if not body:
        raise ValueError("extracted prompt_text is empty")
    return body


def load_note(export_path: Path, note_key: str) -> str:
    obj = json.loads(export_path.read_bytes())
    notes = obj.get("notes")
    if not isinstance(notes, dict) or note_key not in notes:
        raise ValueError(f"notes.{note_key} missing in {export_path}")
    note = notes[note_key]
    if not isinstance(note, str):
        raise ValueError(f"notes.{note_key} is not a string")
    return note


def extract_item(prompt_id: str) -> dict:
    spec = EXTRACTORS[prompt_id]
    export_path = Path(spec["export"])
    if not export_path.is_file():
        raise FileNotFoundError(str(export_path))
    export_sha = sha256_file(export_path)
    expected_export = spec["expected_export_sha256"]
    if export_sha != expected_export:
        raise ValueError(
            f"{export_path} sha256 {export_sha} != expected {expected_export}"
        )
    note = load_note(export_path, spec["note_key"])
    prompt_text = extract_prompt(note, spec["prefix"], spec["suffix"])
    prompt_sha = sha256_text(prompt_text)
    expected_prompt = spec.get("expected_prompt_sha256")
    if expected_prompt and prompt_sha != expected_prompt:
        raise ValueError(
            f"{prompt_id} extracted prompt_sha256 {prompt_sha} != {expected_prompt}"
        )
    return {
        "prompt_id": prompt_id,
        "export_path": str(export_path),
        "export_sha256": export_sha,
        "note_pointer": f"$.notes.{spec['note_key']}",
        "note_sha256": sha256_text(note),
        "prompt_text": prompt_text,
        "prompt_sha256": prompt_sha,
        "prefix": spec["prefix"],
        "suffix": spec["suffix"] or None,
    }


def extract_all() -> dict[str, dict]:
    return {pid: extract_item(pid) for pid in EXTRACTORS}
