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

PROJECT = Path(__file__).resolve().parents[1]
VALIDATOR = PROJECT / "script" / "validate-story-v3.py"
ORIGINALITY_VALIDATOR = PROJECT / "script" / "validate-originality-v3.py"
REPORT = PROJECT / "story" / "v3" / "promotion-report.json"
ORIGINALITY_REPORT = PROJECT / "story" / "v3" / "originality-report.json"
PROJECT_MANIFEST = PROJECT / "script" / "project-manifest.json"
PRODUCTION_PLAN = PROJECT / "script" / "production-plan-v3.json"


def main():
    result = subprocess.run([sys.executable, str(VALIDATOR)], cwd=PROJECT)
    if result.returncode != 0:
        print("Story v3 validation failed; production remains blocked", file=sys.stderr)
        return result.returncode
    originality_result = subprocess.run([sys.executable, str(ORIGINALITY_VALIDATOR)], cwd=PROJECT)
    if originality_result.returncode != 0:
        print("Story v3 originality validation failed; production remains blocked", file=sys.stderr)
        return originality_result.returncode

    report = json.loads(REPORT.read_text(encoding="utf-8"))
    originality = json.loads(ORIGINALITY_REPORT.read_text(encoding="utf-8"))
    if originality.get("verified") is not True or originality.get("source_canon_sha256") != report.get("spoken_sha256"):
        print("Originality report is not verified or canon hash mismatched", file=sys.stderr)
        return 1
    if report.get("verified") is not True or report.get("status") != "passed":
        print("Promotion report is not verified", file=sys.stderr)
        return 1

    canon_hash = report.get("spoken_sha256")
    if not canon_hash:
        print("Promotion report has no canon hash", file=sys.stderr)
        return 1

    now = datetime.now(timezone.utc).isoformat()
    plan = json.loads(PRODUCTION_PLAN.read_text(encoding="utf-8"))
    if plan.get("outline_sha256") is None or plan.get("reuse_v2") is not False:
        print("Production plan invariant failed", file=sys.stderr)
        return 1
    plan["status"] = "story_promoted_ready_for_tts"
    plan["canon_sha256"] = canon_hash
    plan["story_words"] = report["total_words"]
    plan["story_estimated_minutes"] = report["estimated_minutes_at_baseline"]
    plan["promoted_at"] = now

    manifest = json.loads(PROJECT_MANIFEST.read_text(encoding="utf-8"))
    if manifest.get("rewrite", {}).get("version") != 3:
        print("Project manifest is not in rewrite v3 mode", file=sys.stderr)
        return 1
    manifest["status"] = "story_v3_promoted"
    manifest["canon_version"] = 3
    manifest["canon_authority"] = "story/v3/spoken-narration.txt"
    manifest["canon_hash"] = canon_hash
    manifest["story_word_count"] = report["total_words"]
    manifest["steps"]["story"] = "completed"
    manifest["steps"]["tts"] = "pending"
    manifest["rewrite"]["status"] = "promoted"
    manifest["updated_at"] = now

    # Write only after every invariant passes, so validation failure changes no authority.
    PRODUCTION_PLAN.write_text(json.dumps(plan, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    PROJECT_MANIFEST.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(json.dumps({
        "promoted": True,
        "canon_sha256": canon_hash,
        "words": report["total_words"],
        "estimated_minutes": report["estimated_minutes_at_baseline"],
        "next_step": "script/render-tts-v3.py",
    }, ensure_ascii=False))
    return 0


if __name__ == "__main__":
    sys.exit(main())
