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

import hashlib
import json
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"
TITLE = "Ngày Bưu Cục Cũ Sáng Đèn"
OUTPUT = ROOT / "output" / "info.txt"
RECEIPT = ROOT / "log" / "metadata.json"


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


def sha(path: Path) -> str:
    h = hashlib.sha256()
    with path.open("rb") as f:
        for block in iter(lambda: f.read(8 * 1024 * 1024), b""):
            h.update(block)
    return h.hexdigest()


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


def main() -> None:
    guard()
    promotion_path = ROOT / "script" / "promotion-report.json"
    brief_path = ROOT / "script" / "story-brief.json"
    promotion = json.loads(promotion_path.read_text(encoding="utf-8"))
    brief = json.loads(brief_path.read_text(encoding="utf-8"))
    if promotion.get("verified") is not True or promotion.get("status") not in {"passed", "completed", "completed_content_only"}:
        raise RuntimeError("promotion gate is not verified")
    canon = ROOT / "story" / "story-canon.txt"
    canon_hash = promotion.get("canon_sha256") or promotion.get("source_canon_sha256")
    if sha(canon) != canon_hash:
        raise RuntimeError("canon hash mismatch")
    brief_text = json.dumps(brief, ensure_ascii=False)
    if TITLE not in brief_text:
        raise RuntimeError("canonical title missing from story brief")
    summary = (
        "Khi mưa lũ cắt toàn bộ mạng di động của huyện Vân Khê, kỹ sư liên lạc khẩn cấp Trình Vãn Ý "
        "buộc phải tái mở bưu cục cũ và dựng một mạng chuyển tin bằng giấy cùng Lục Trầm Chu, người "
        "phát thư đường núi từng là vị hôn phu của cô. Một phiếu báo giả mang con dấu đỏ khiến họ "
        "phải chạy đua để bảo vệ người dân, đồng thời học lại cách trao niềm tin mà không quyết định thay nhau."
    )
    title_line = f"Truyện Audio | {TITLE} (Full) | Hạ Trâm Audio"
    description = f"""Bạn đang lắng nghe {TITLE} tại Hạ Trâm Audio.

Tóm tắt truyện:
{summary}

🎧 Tên truyện: {TITLE}
🎙 Giọng đọc: Hạ Trâm Audio
📚 Thể loại: Ngôn tình đô thị, cứu hộ đời thường, chữa lành, drama
Tình trạng: Trọn bộ

Nếu yêu thích câu chuyện, hãy đăng ký kênh và để lại cảm nhận của bạn dưới phần bình luận.

Hạ Trâm Audio – Lắng nghe một thế giới khác.

#HaTramAudio #TruyenAudio #NgonTinh #ChuaLanh #TruyenFull
"""
    content = title_line + "\n\n" + description
    OUTPUT.parent.mkdir(parents=True, exist_ok=True)
    guard()
    OUTPUT.write_text(content, encoding="utf-8")
    receipt = {
        "schema_version": 1,
        "project_id": PROJECT_ID,
        "run_id": RUN_ID,
        "status": "completed",
        "verified": True,
        "source_canon_sha256": canon_hash,
        "source_story_brief_sha256": sha(brief_path),
        "canonical_title": TITLE,
        "youtube_title": title_line,
        "title_length": len(title_line),
        "summary": summary,
        "genres": ["Ngôn tình đô thị", "Cứu hộ đời thường", "Chữa lành", "Drama"],
        "artifact_path": str(OUTPUT),
        "artifact_sha256": sha(OUTPUT),
        "contains_spoiler_reveal": False,
        "completed_at": now(),
    }
    guard()
    RECEIPT.write_text(json.dumps(receipt, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(json.dumps({"status": "completed", "verified": True, "title": title_line, "artifact_sha256": receipt["artifact_sha256"]}, ensure_ascii=False))


if __name__ == "__main__":
    main()
