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

PROJECT = Path(__file__).resolve().parents[1]
OUTLINE = PROJECT / "story" / "v3" / "outline.json"
PROMOTION = PROJECT / "story" / "v3" / "promotion-report.json"
NARRATION = PROJECT / "story" / "v3" / "spoken-narration.txt"
OUTPUT = PROJECT / "image" / "v3" / "image-brief.json"


def main():
    if not all(path.exists() for path in (OUTLINE, PROMOTION, NARRATION)):
        print("Image brief blocked: promoted story authority missing", file=sys.stderr)
        return 1
    outline = json.loads(OUTLINE.read_text(encoding="utf-8"))
    promotion = json.loads(PROMOTION.read_text(encoding="utf-8"))
    canon_hash = hashlib.sha256(NARRATION.read_bytes()).hexdigest()
    if promotion.get("verified") is not True or promotion.get("spoken_sha256") != canon_hash:
        print("Image brief blocked: story v3 is not promoted or hash mismatched", file=sys.stderr)
        return 1

    title = outline["canonical_title"]
    registry = outline["identity_registry"]
    reveal = outline["reveal_ledger"]
    required_right = [
        "Huyền An Audio",
        title,
        "Truyện được phát độc quyền tại Huyền An Audio, nghiêm cấm sao chép dưới mọi hình thức",
    ]
    brief = {
        "version": 3,
        "verified": True,
        "source_canon_sha256": canon_hash,
        "canonical_title": title,
        "genre": ["drama Trung Quốc hư cấu", "nghi oan công sở", "đấu trí", "phản công"],
        "core_conflict": "Một nữ kế toán kiểm soát bị mười hai đồng nghiệp ký lời buộc tội biển thủ quỹ cứu trợ; các chữ ký và sổ đối chiếu trở thành motif gây căng thẳng nhưng không lộ cơ chế phản chủ.",
        "protagonist": "Hứa Thanh Nghi, nữ kế toán châu Á hư cấu khoảng 28 tuổi, tóc đen buộc thấp, vest xanh than, sơ mi sáng, vẻ bình tĩnh nhưng chịu áp lực, cầm bút máy và cuốn sổ đối chiếu màu xanh.",
        "supporting_cast": [
            "Tống Mộng Dao, nữ lãnh đạo vận hành khoảng 38 tuổi, vest đỏ sẫm, khí chất quyền lực lạnh",
            "Lục Khải Minh, nam trưởng phòng tài chính khoảng 42 tuổi, vest tối màu, vẻ tự tin che giấu căng thẳng",
        ],
        "world": "Trụ sở quỹ cứu trợ hư cấu tại Lâm Giang trong đêm mưa, văn phòng kính, hồ sơ giải ngân, thùng hàng cứu trợ và skyline xa.",
        "motifs": ["mười hai nét chữ ký đỏ", "sổ đối chiếu màu xanh", "hồ sơ cứu trợ", "dòng số liệu kế toán", "mưa trên kính"],
        "palette": "navy, charcoal, teal tối; điểm vàng kem và đỏ son có kiểm soát; không tím mặc định",
        "reveal_limit": {
            "allowed": reveal["allowed_early"],
            "forbidden": reveal["protected_until_climax"],
        },
        "assets": {
            "intro_poster": {
                "size": [1920, 1080],
                "composition": "Key art điện ảnh 16:9; vùng chữ sạch bên trái; Thanh Nghi trung tâm-phải; Mộng Dao và Khải Minh lùi sau; motif chữ ký không cho biết ai thắng.",
                "required_text": required_right,
                "output": "image/v3/intro-poster-master.png",
            },
            "right_panel": {
                "master_ratio": "1080:1778",
                "target_size": [656, 1080],
                "composition": "Poster dọc hoàn chỉnh, không crop poster ngang; Thanh Nghi là focal point, title và dòng độc quyền nằm trong safe margin 7%.",
                "required_text": required_right,
                "output": "image/v3/right-panel-master.png",
            },
            "left_panel": {
                "master_ratio": "1080:1778",
                "target_size": [656, 1080],
                "composition": "Branding panel không nhân vật, không title truyện, dùng motif sổ và chữ ký ở mức trang trí.",
                "required_text": ["Huyền An Audio", "Like • Chia sẻ • Đăng ký"],
                "forbidden_text": [title, required_right[2]],
                "output": "image/v3/left-panel-master.png",
            },
        },
        "identity_registry": registry,
        "negative_constraints": [
            "Không logo hoặc thương hiệu thật",
            "Không người nổi tiếng",
            "Không reveal token dự phòng, bản ghi gốc, thiết bị ký chung, dòng tiền cuối hoặc lợi ích đổi chữ ký",
            "Không sai chính tả hoặc thiếu dấu ở khối chữ chính",
            "Không giao provider dựng layout ba panel",
        ],
        "created_at": datetime.now(timezone.utc).isoformat(),
    }
    OUTPUT.parent.mkdir(parents=True, exist_ok=True)
    OUTPUT.write_text(json.dumps(brief, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
    print(json.dumps({"verified": True, "source_canon_sha256": canon_hash, "output": str(OUTPUT)}, ensure_ascii=False))
    return 0


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