#!/usr/bin/env python3
import hashlib
import json
import sys
from pathlib import Path

PROJECT = Path(__file__).resolve().parents[1]
AUTHORITY = PROJECT / "script/workflow-copy-authority.json"
INTRO_SOURCE = PROJECT / "audio/intro-voice-source.txt"
IMAGE_BRIEF = PROJECT / "image/image-brief.json"


def sha_bytes(data):
    return hashlib.sha256(data).hexdigest()


def load(path):
    return json.loads(path.read_text(encoding="utf-8"))


def main():
    mode = sys.argv[1] if len(sys.argv) > 1 else "pre-provider"
    if mode not in {"pre-provider", "full"}:
        raise RuntimeError("mode must be pre-provider or full")
    authority = load(AUTHORITY)
    intro = authority.get("spoken_intro", {})
    left = authority.get("left_panel", {})
    intro_text = intro.get("exact_text")
    blocks = left.get("ordered_text_blocks")
    issues = []
    if authority.get("approval_state") != "locked":
        issues.append("authority_not_locked")
    if not isinstance(intro_text, str) or not intro_text.endswith("\n") or intro.get("sha256") != sha_bytes(intro_text.encode("utf-8")):
        issues.append("intro_authority_invalid")
    if not isinstance(blocks, list) or len(blocks) != 2 or not all(isinstance(x, str) and x for x in blocks):
        issues.append("left_panel_authority_invalid")
    elif left.get("block_sha256") != [sha_bytes(x.encode("utf-8")) for x in blocks]:
        issues.append("left_panel_authority_hash_mismatch")
    if not INTRO_SOURCE.is_file() or INTRO_SOURCE.read_text(encoding="utf-8") != intro_text:
        issues.append("intro_source_drift")
    if not IMAGE_BRIEF.is_file():
        issues.append("image_brief_missing")
    else:
        brief = load(IMAGE_BRIEF)
        actual = brief.get("assets", {}).get("left_panel", {}).get("required_text")
        if actual != blocks:
            issues.append("left_panel_brief_drift")
        if brief.get("workflow_copy_authority_sha256") != sha_bytes(AUTHORITY.read_bytes()):
            issues.append("image_brief_authority_binding_missing_or_stale")
    if mode == "full":
        for rel in ("log/intro-tts-pronunciation.json", "log/intro-voice.json", "log/image-generation.json", "log/image-visual-qa.json", "image/layout-manifest.json"):
            path = PROJECT / rel
            if not path.is_file():
                issues.append("missing_receipt:" + rel)
                continue
            row = load(path)
            if row.get("workflow_copy_authority_sha256") != sha_bytes(AUTHORITY.read_bytes()):
                issues.append("receipt_authority_binding_missing_or_stale:" + rel)
    result = {"verified": not issues, "mode": mode, "workflow_copy_authority_sha256": sha_bytes(AUTHORITY.read_bytes()), "issues": issues}
    print(json.dumps(result, ensure_ascii=False))
    return 0 if not issues else 1


if __name__ == "__main__":
    try:
        raise SystemExit(main())
    except Exception as exc:
        print(f"Workflow copy validation blocked: {exc}", file=sys.stderr)
        raise SystemExit(1)
