#!/usr/bin/env python3
from __future__ import annotations

import hashlib
import json
import re
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path("/data/video-pipeline/HaTramAudio/project/013-Ngay-Buu-Cuc-Cu-Sang-Den")
PROJECT_ID = "013-Ngay-Buu-Cuc-Cu-Sang-Den"
RUN_ID = "run-20260720T110344Z-f6c08be9"
OWNER = "zoro"
CANDIDATE = ROOT / "work" / "story" / RUN_ID / "candidate.txt"
CANON = ROOT / "story" / "story-canon.txt"
NARRATION = ROOT / "story" / "spoken-narration.txt"
REPORT = ROOT / "work" / "story" / RUN_ID / "validation-independent.json"
AUTHORITY = [
    "script/creative-options.json",
    "script/story-brief.json",
    "script/outline.json",
    "script/identity-registry.json",
    "script/reveal-ledger.json",
    "script/continuity-ledger.json",
    "script/originality-report.json",
    "script/story-qa.json",
    "script/promotion-report.json",
    "script/story-manifest.json",
]


def now() -> str:
    return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")


def sha(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def guard() -> None:
    lock = json.loads((ROOT / ".ownership-lock.json").read_text(encoding="utf-8"))
    expected = {"project_id": PROJECT_ID, "run_id": RUN_ID, "owner": OWNER, "status": "active"}
    for key, value in expected.items():
        if lock.get(key) != value:
            raise RuntimeError(f"ownership mismatch: {key}")


def main() -> int:
    guard()
    missing = [str(path) for path in [CANDIDATE, CANON, NARRATION] if not path.is_file()]
    missing += [rel for rel in AUTHORITY if not (ROOT / rel).is_file()]
    if missing:
        raise RuntimeError("story authority incomplete: " + ", ".join(missing))
    candidate = CANDIDATE.read_bytes()
    canon = CANON.read_bytes()
    narration = NARRATION.read_bytes()
    text = narration.decode("utf-8")
    word_count = len(re.findall(r"\b\w+\b", text, flags=re.UNICODE))
    duration = word_count / 231
    json_docs = {}
    for rel in AUTHORITY:
        json_docs[rel] = json.loads((ROOT / rel).read_text(encoding="utf-8"))
    promotion = json_docs["script/promotion-report.json"]
    story_qa = json_docs["script/story-qa.json"]
    hashes_equal = candidate == canon == narration
    content_markers = {
        "markdown_heading": bool(re.search(r"(?m)^#{1,6}\s", text)),
        "chapter_heading": bool(re.search(r"(?mi)^\s*(chương|phần|hồi)\s+[0-9ivxlcdm]+\b", text)),
        "channel_cta": bool(re.search(r"(?i)(đăng ký kênh|like video|hạ trâm audio)", text)),
        "metadata_label": bool(re.search(r"(?mi)^\s*(tiêu đề|mô tả|hashtag|thể loại)\s*:", text)),
    }
    canon_hash = sha(canon)
    narration_hash = sha(narration)
    promotion_hash_ok = (promotion.get("canon_sha256") or promotion.get("source_canon_sha256")) == canon_hash
    narration_hash_ok = promotion.get("spoken_narration_sha256") == narration_hash
    checks = {
        "candidate_canon_narration_byte_identical": hashes_equal,
        "word_count_in_9240_13860": 9240 <= word_count <= 13860,
        "duration_in_40_60_at_231_wpm": 40 <= duration <= 60,
        "promotion_verified": promotion.get("verified") is True and promotion.get("status") in {"passed", "completed", "completed_content_only"},
        "promotion_canon_hash_matches": promotion_hash_ok,
        "promotion_narration_hash_matches": narration_hash_ok,
        "story_qa_verified": story_qa.get("verified") is True and story_qa.get("status") in {"passed", "completed", "passed_content_scope"},
        "no_forbidden_narration_markers": not any(content_markers.values()),
        "canonical_title_present_in_brief": "Ngày Bưu Cục Cũ Sáng Đèn" in json.dumps(json_docs["script/story-brief.json"], ensure_ascii=False),
    }
    report = {
        "schema_version": 1,
        "project_id": PROJECT_ID,
        "run_id": RUN_ID,
        "status": "passed" if all(checks.values()) else "failed",
        "verified": all(checks.values()),
        "checks": checks,
        "content_markers": content_markers,
        "word_count": word_count,
        "planning_words_per_minute": 231,
        "estimated_duration_minutes": duration,
        "candidate_sha256": sha(candidate),
        "canon_sha256": canon_hash,
        "spoken_narration_sha256": narration_hash,
        "authority_sha256": {rel: sha((ROOT / rel).read_bytes()) for rel in AUTHORITY},
        "validated_at": now(),
    }
    guard()
    REPORT.parent.mkdir(parents=True, exist_ok=True)
    REPORT.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(json.dumps(report, ensure_ascii=False))
    return 0 if report["verified"] else 1


if __name__ == "__main__":
    raise SystemExit(main())
