#!/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]
AUTHORITY = PROJECT / "script/workflow-copy-authority.json"
STORY_BRIEF = PROJECT / "script/story-brief.json"
PROMOTION = PROJECT / "story/promotion-report.json"
OUTPUT = PROJECT / "image/image-brief.json"


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


def main():
    authority = json.loads(AUTHORITY.read_text(encoding="utf-8"))
    story = json.loads(STORY_BRIEF.read_text(encoding="utf-8"))
    promotion = json.loads(PROMOTION.read_text(encoding="utf-8"))
    if authority.get("approval_state") != "locked" or promotion.get("verified") is not True:
        raise RuntimeError("locked copy authority and promoted story required")
    left = authority["left_panel"]["ordered_text_blocks"]
    title = story["canonical_title"]
    common = {
        "source_canon_sha256": promotion["canon_sha256"],
        "workflow_copy_authority_sha256": sha(AUTHORITY),
        "workflow_copy_revision": authority["revision"],
    }
    brief = {
        "version": 1,
        "verified": True,
        **common,
        "style_lock": "cinematic contemporary Chinese romantic drama, warm paper-and-rain palette, realistic fictional adults, no real person",
        "assets": {
            "intro_poster": {
                "asset_type": "opening_render",
                "required_text": [title],
                "prompt": "Wide 16:9 cinematic poster inside an old Suzhou community bookshop on a rainy morning. Fictional adult Chinese woman book conservator and adult Chinese male preservation architect stand on opposite sides of a wooden counter, respectful distance, an unopened aged letter and swallow-shaped lending stamp visible. Render exactly one Vietnamese title block: " + title + ". No other readable text, no watermark, no logo, no love triangle, no third romantic figure."
            },
            "right_panel": {
                "asset_type": "poster",
                "required_text": [title],
                "prompt": "Tall portrait cinematic poster for a contemporary Suzhou audio romance. Exact cast count two: one adult Chinese woman book conservator in foreground holding an unopened old letter, one adult Chinese male preservation architect beside but not shielding her; equal agency, warm old-bookshop light, swallow stamp motif. Render exactly one Vietnamese title block: " + title + ". No other readable text, no watermark, no triangle composition, no extra woman."
            },
            "left_panel": {
                "asset_type": "social_image",
                "required_text": left,
                "prompt": "Abstract premium channel-branding panel, warm dark teal and antique gold paper texture, subtle non-readable swallow and sound-wave geometry. No people, no face, no silhouette, no bookshop scene, no letter, no story title, no signs, no pseudo-text. Render exactly two separate Vietnamese text blocks and no other readable characters: 1) " + left[0] + " 2) " + left[1] + ". Preserve exact accents and bullet punctuation."
            }
        },
        "created_at": datetime.now(timezone.utc).isoformat(),
    }
    OUTPUT.parent.mkdir(parents=True, exist_ok=True)
    tmp = OUTPUT.with_name(OUTPUT.name + ".part")
    tmp.write_text(json.dumps(brief, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    os.replace(tmp, OUTPUT)
    print(json.dumps({"verified": True, "output": str(OUTPUT), **common}, ensure_ascii=False))


if __name__ == "__main__":
    main()
