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

PROJECT = Path(__file__).resolve().parents[1]
BRIEF = PROJECT / "script/story-brief.json"
PROMOTION = PROJECT / "story/promotion-report.json"
OUT = PROJECT / "output/info.txt"
RECEIPT = PROJECT / "log/metadata-verification.json"


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


def main():
    brief = json.loads(BRIEF.read_text(encoding="utf-8"))
    promotion = json.loads(PROMOTION.read_text(encoding="utf-8"))
    if promotion.get("verified") is not True or promotion.get("canon_sha256") != sha(PROJECT / "story/story-canon.txt"):
        raise RuntimeError("promoted canon required")
    title = brief["canonical_title"]
    description = (
        "Tiệm sách cộng đồng sắp đóng cửa buộc Tống Nghiên Thư hợp tác với Lục Hoài Cẩn, "
        "người bạn thanh mai đã giữ một lá thư suốt mười hai năm. Giữa ký ức, quyền lựa chọn "
        "và tương lai của cả khu phố, họ phải học cách đứng cạnh nhau mà không quyết định thay nhau.\n\n"
        "#HuyenAnAudio #TruyenAudio #NgonTinh #ThanhMaiTrucMa"
    )
    data = title + "\n\n" + description + "\n"
    OUT.parent.mkdir(parents=True, exist_ok=True)
    tmp = OUT.with_name(OUT.name + ".part")
    tmp.write_text(data, encoding="utf-8")
    os.replace(tmp, OUT)
    receipt = {"version": 1, "verified": True, "status": "completed", "source_canon_sha256": promotion["canon_sha256"], "publishing_title": title, "title_length": len(title), "path": str(OUT.relative_to(PROJECT)), "sha256": sha(OUT), "format": "title + blank line + description", "checked_at": datetime.now(timezone.utc).isoformat()}
    RECEIPT.parent.mkdir(parents=True, exist_ok=True)
    tmp = RECEIPT.with_name(RECEIPT.name + ".part")
    tmp.write_text(json.dumps(receipt, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    os.replace(tmp, RECEIPT)
    print(json.dumps(receipt, ensure_ascii=False))


if __name__ == "__main__":
    main()
