#!/usr/bin/env python3
import hashlib
import json
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path

PROJECT = Path(__file__).resolve().parents[1]
CANON = PROJECT / "story/story-canon.txt"
SPOKEN = PROJECT / "story/spoken-narration.txt"
REPORT = PROJECT / "story/draft-report.json"
ORIGINALITY = PROJECT / "story/originality-report.json"
OUT = PROJECT / "story/promotion-report.json"
AUTHORITY = [
    PROJECT / "script/story-brief.json",
    PROJECT / "script/outline.json",
    PROJECT / "script/story-ledger.json",
    PROJECT / "script/identity-registry.json",
    PROJECT / "script/reveal-ledger.json",
    PROJECT / "script/production-plan.json",
]


def sha(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def main():
    subprocess.run([sys.executable, str(PROJECT / "script/validate-story.py")], check=True)
    subprocess.run([sys.executable, str(PROJECT / "script/validate-originality.py")], check=True)
    report = json.loads(REPORT.read_text(encoding="utf-8"))
    originality = json.loads(ORIGINALITY.read_text(encoding="utf-8"))
    brief = json.loads(AUTHORITY[0].read_text(encoding="utf-8"))
    if CANON.read_bytes() != SPOKEN.read_bytes():
        raise RuntimeError("canon/spoken bytes differ")
    if originality.get("verified") is not True or originality.get("primary_story_family_preserved") is not True:
        raise RuntimeError("originality/family gate failed")
    authority = {str(path.relative_to(PROJECT)): sha(path) for path in AUTHORITY}
    word_count = report.get("word_count", report.get("spoken_word_count", report.get("aggregate_word_count")))
    chapter_count = report.get("chapters", report.get("chapters_present", len(report.get("chapter_rows", []))))
    receipt = {
        "version": 1,
        "verified": True,
        "status": "passed",
        "project_id": brief["project_id"],
        "canonical_title": brief["canonical_title"],
        "primary_story_family": brief["primary_story_family"],
        "secondary_story_family": brief["secondary_story_family"],
        "canon_path": str(CANON.relative_to(PROJECT)),
        "canon_sha256": sha(CANON),
        "spoken_path": str(SPOKEN.relative_to(PROJECT)),
        "spoken_sha256": sha(SPOKEN),
        "word_count": word_count,
        "chapters": chapter_count,
        "duration_minutes_at_231_wpm": round(word_count / 231, 3),
        "authority_hashes": authority,
        "originality_report_sha256": sha(ORIGINALITY),
        "originality_verified": True,
        "family_adherence_verified": True,
        "promoted_at": datetime.now(timezone.utc).isoformat(),
    }
    OUT.write_text(json.dumps(receipt, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    manifest_path = PROJECT / "script/project-manifest.json"
    manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
    manifest["status"] = "story_promoted_ready_for_pronunciation"
    manifest["canon_sha256"] = receipt["canon_sha256"]
    manifest["word_count"] = receipt["word_count"]
    manifest["steps"]["story"] = "completed"
    manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(json.dumps(receipt, ensure_ascii=False))
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except Exception as exc:
        print(f"Promotion blocked: {exc}", file=sys.stderr)
        sys.exit(1)
