#!/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/014-Nguoi-Ve-Ban-Do-Mua-Dong")
PROJECT_ID = "014-Nguoi-Ve-Ban-Do-Mua-Dong"
RUN_ID = "run-20260720T152357Z-c85a2128"
OWNER = "zoro"
TITLE = "Người Vẽ Bản Đồ Mùa Đông"
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": "main_session_pipeline"}.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 = (
        "Trong kho lưu trữ tàu điện của một thành phố phía bắc phủ tuyết, chuyên viên phục chế Trình Tố Nghi "
        "phát hiện một tuyến đường đã bị xóa khỏi bản đồ cũ. Muốn lần theo những nét mực xanh bất thường, cô "
        "phải hợp tác với kiểm toán viên an toàn đường sắt Lục Hoài Xuyên, người đang mang một chữ ký khiến cô "
        "không thể hoàn toàn tin tưởng. Giữa hồ sơ thất lạc và những sân ga mùa đông, họ học cách trao sự thật "
        "mà không tước quyền lựa chọn của 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ị, bí ẩn nghề nghiệp, 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ị", "Bí ẩn nghề nghiệp", "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()
