# -*- coding: utf-8 -*-
"""
tools/build_character_turnarounds_master.py
Khởi tạo và biên soạn toàn bộ danh mục Turnaround Model Sheet 4 góc nhìn chuẩn studio
cho toàn bộ dàn nhân vật cốt lõi của Đông A Hùng Ký (Tran_Empire).
"""

import os
import sys
import json
from pathlib import Path

if hasattr(sys.stdout, 'reconfigure'):
    sys.stdout.reconfigure(encoding='utf-8')

BASE_DIR = Path(__file__).resolve().parent.parent
OUTPUT_JSON = BASE_DIR / "02_AI_Prompts" / "character_turnaround_sheets_master.json"
CHARACTERS_ASSETS_DIR = BASE_DIR / "04_Assets" / "characters"

TURNAROUND_TEMPLATE_PREFIX = (
    "Professional character turnaround model sheet, production-ready 3D CGI character design sheet, "
    "multiple orthographic views of the SAME character on a single horizontal layout: "
    "far left close-up front bust portrait showing refined facial features, "
    "center-left full-body right side profile view standing straight, "
    "center-right full-body front view in neutral standing A-pose, "
    "far right full-body back view showing hair and back robe drape. "
)

TURNAROUND_TEMPLATE_SUFFIX = (
    " Studio Setup: Pure clean white background, seamless studio backdrop, even diffuse cinematic studio lighting, "
    "soft subtle contact shadows on the floor, no background props, no environment. "
    "Style: Unreal Engine 5 Metahuman render, hyper-detailed ZBrush cloth sculpt, Maya xGen groom, Octane Render 8K UHD, photorealistic CGI character asset, authentic 13th century Dai Viet Tran Dynasty historical archaeology --ar 16:9"
)

CHARACTER_DATA = [
    # 01. Nhóm Khởi nguyên Hải Ấp (Dành riêng cho Tập 1 & Mùa 1)
    {
        "id": "tran_ly_50yo",
        "name_vn": "Trần Lý (50 tuổi)",
        "role": "Tộc trưởng họ Trần, Thuyền chủ Hải Ấp, phụ thân Trần Tự Khánh & Trần Thị Dung",
        "folder": "01_Founders_And_Hai_Ap/tran_ly_50yo",
        "appearance": "50-year-old commanding Vietnamese fishing clan patriarch, weathered sun-baked bronze skin, strong square jaw with distinguished pepper-and-salt beard, hair tied in traditional Thoan Ke topknot with horn comb, piercing intelligent observant eyes.",
        "costume": "Authentic 13th-century Dai Viet coarse cinnamon-brown Giao Linh cross-collar linen robe, unadorned hemp waist tie, woven palm-leaf shoulder cape (ao toi), barefoot standing on floor showing bare weathered feet, full-thigh and forearm intricate dark indigo Giao Long water-dragon tattoos.",
        "weapons": "Bronze-hilted short hunting broadsword in carved wood scabbard at hip."
    },
    {
        "id": "tran_tu_khanh_25yo",
        "name_vn": "Trần Tự Khánh (25 tuổi)",
        "role": "Trưởng nam của Trần Lý, Đại tướng thủy quân dũng mãnh, Chương Thành hầu",
        "folder": "01_Founders_And_Hai_Ap/tran_tu_khanh_25yo",
        "appearance": "25-year-old powerfully built Vietnamese heroic general, broad muscular shoulders, fierce courageous eyes, sharp jawline, high topknot secured with bronze hairpin, athletic posture.",
        "costume": "Reinforced dark indigo-dyed linen tunic under a hardened boiled-leather brigandine vest laced with bronze studs, dark linen trousers, barefoot, prominent traditional Giao Long dragon tattoos wrapping around powerful calves and thighs.",
        "weapons": "Holding a massive curved Tran-dynasty iron-hilted broad saber (dai dao) with engraved bronze dragon guard."
    },
    {
        "id": "tran_thu_do_young_18yo",
        "name_vn": "Trần Thủ Độ - Thời thiếu niên (18 tuổi)",
        "role": "Cháu ruột Trần Lý, thiếu niên thiên tài quân sự và chính trị",
        "folder": "01_Founders_And_Hai_Ap/tran_thu_do_young_18yo",
        "appearance": "18-year-old lean athletic Vietnamese youth with an intense calculating presence, chiseled sharp jawline, piercing eagle eyes radiating profound strategic intellect, neat black topknot.",
        "costume": "Fitted sleeveless dark navy and charcoal Giao Linh tunic, raw hemp belt, barefoot, full muscular arms and thighs covered in sharp indigo Giao Long serpentine water-dragon tattoos.",
        "weapons": "Concealed classic Tran bronze short dagger with curved lotus blade tucked into waist belt."
    },
    {
        "id": "tran_thi_dung_maiden_16yo",
        "name_vn": "Trần Thị Dung - Thiếu nữ (16 tuổi)",
        "role": "Con gái Trần Lý, tuyệt sắc giai nhân sông nước Hải Triều, sau là Hoàng hậu",
        "folder": "01_Founders_And_Hai_Ap/tran_thi_dung_maiden_16yo",
        "appearance": "16-year-old breathtakingly beautiful Vietnamese coastal maiden, fair luminous porcelain skin, delicate oval face, gentle sorrowful almond eyes reflecting autumn water, long flowing silky raven-black hair tied with a simple polished wooden hairpin.",
        "costume": "Layered pastel lotus-yellow and unbleached ivory raw silk Giao Linh cross-collar robe, soft flowing draped sleeves, slender woven fabric waist sash with delicate mother-of-pearl fish pendant, delicate barefoot stance.",
        "weapons": "Carrying a woven bamboo tray with celadon tea bowl."
    },
    {
        "id": "thuy_binh_tran_giao_long",
        "name_vn": "Tráng đinh Thủy quân họ Trần (Mẫu hình chung)",
        "role": "Quân sĩ dân chài tinh nhuệ họ Trần vùng sông nước Hải Ấp",
        "folder": "01_Founders_And_Hai_Ap/thuy_binh_tran_giao_long",
        "appearance": "22-year-old vigorous muscular Vietnamese river warrior, deeply tanned bronze skin, determined fearless expression, short cropped topknot.",
        "costume": "Bare-chested wearing traditional dark brown woven linen loincloth (dong kho), entirely barefoot, dense intricate dark indigo Giao Long sea-monster tattoos wrapping around entire thighs, legs, and forearms.",
        "weapons": "Holding a heavy bamboo spear with bronze leaf-blade and woven rattan buckler shield."
    },

    # 02. Nhóm Hoàng gia & Biến loạn triều Lý (Tập 1)
    {
        "id": "thai_tu_ly_sam_16yo",
        "name_vn": "Thái tử Lý Sảm (16 tuổi)",
        "role": "Thái tử lưu vong nhà Lý, sau là vua Lý Huệ Tông",
        "folder": "02_Imperial_Ly_Dynasty/thai_tu_ly_sam_16yo",
        "appearance": "16-year-old refined handsome Vietnamese prince, pale complexion, sensitive sorrowful almond eyes, delicate aristocratic features, youthful disheveled black topknot.",
        "costume": "Stained and torn pale apricot-yellow embroidered royal silk Giao Linh robe, disheveled frayed collar, tarnished silver-embossed leather waist belt with chipped jade pendant, barefoot with dirt-stained soles.",
        "weapons": "Clutching an ancestral imperial jade seal pouch."
    },
    {
        "id": "ly_cao_tong_40yo",
        "name_vn": "Vua Lý Cao Tông (40 tuổi)",
        "role": "Hoàng đế suy tàn cuối đời triều Lý, hoang dâm u mê",
        "folder": "02_Imperial_Ly_Dynasty/ly_cao_tong_40yo",
        "appearance": "40-year-old haggard gaunt Vietnamese monarch, sunken hollow eyes with dark circles of exhaustion and terror, unkempt thin beard, drooping posture.",
        "costume": "Creased and mud-splattered imperial yellow silk robe with faded embroidered four-claw dragons, crooked gold dragon crown with loosened pearl strands, scuffed embroidered cloth boots.",
        "weapons": "Empty tremulous hands."
    },
    {
        "id": "dam_thai_hau",
        "name_vn": "Đàm Thái Hậu",
        "role": "Thái hậu triều Lý, mẹ vua Huệ Tông, bảo thủ, thâm độc, thù ghét họ Trần",
        "folder": "02_Imperial_Ly_Dynasty/dam_thai_hau",
        "appearance": "48-year-old imperious severe Vietnamese royal dowager, sharp aristocratic cheekbones, haughty disdainful dark eyes, elaborate high coiled royal coiffure adorned with ornate gold phoenix hairpins.",
        "costume": "Luxurious multi-layered crimson and gold brocade Giao Linh ceremonial court robe with wide stiffened collar, heavy gold belt with dangling jade talismans, pointed velvet slippers.",
        "weapons": "Holding an ivory and sandalwood folding fan."
    },
    {
        "id": "quach_boc",
        "name_vn": "Quách Bốc",
        "role": "Tướng phản quân chiếm Thăng Long, đầu sỏ bạo loạn",
        "folder": "02_Imperial_Ly_Dynasty/quach_boc",
        "appearance": "38-year-old brutal burly Vietnamese rebel warlord, scarred weathered face, sinister predatory eyes, scruffy unkempt beard, red bandana tied around disheveled topknot.",
        "costume": "Mismatched captured iron lamellar armor plates over crude dark hemp tunic, heavy iron belt, studded leather arm bracers, muddy boots.",
        "weapons": "Holding a blood-stained broad iron falchion."
    },

    # 03. Nhóm Hào kiệt Đông A & Kháng chiến Mông Cổ
    {
        "id": "tran_thu_do_leader_45yo",
        "name_vn": "Thái sư Trần Thủ Độ (45 tuổi)",
        "role": "Thống quốc Thái sư, Tiết chế quân sự, khai quốc công thần số một",
        "folder": "03_Dong_A_War_Heroes/tran_thu_do_leader_45yo",
        "appearance": "45-year-old imposing powerful Vietnamese Grand Preceptor, chiseled square jawline, piercing eagle eyes, short trimmed neat black beard, determined stoic unyielding expression.",
        "costume": "Deep indigo cross-collar Giao Linh silk robe with wide lapels, dark leather belt with antique bronze buckle, hand resting on bronze longsword hilt, sturdy leather half-boots.",
        "weapons": "Classic Tran-dynasty bronze-hilted longsword with carved dragon pommel."
    },
    {
        "id": "tran_quoc_tuan_55yo",
        "name_vn": "Hưng Đạo Đại Vương Trần Quốc Tuấn (55 tuổi)",
        "role": "Tiết chế Thống lĩnh chư quân, thiên tài quân sự thế giới",
        "folder": "03_Dong_A_War_Heroes/tran_quoc_tuan_55yo",
        "appearance": "55-year-old legendary dignified supreme commander, weathered handsome face marked by strategic wisdom, long flowing grey-streaked beard reaching his chest, eyes shining like the North Star.",
        "costume": "Ornate blackened iron lamellar plate armor laced with dark red silk cords, polished bronze lotus heart-mirror on chest, deep crimson commander cloak with gold dragon embroidery, leather riding boots.",
        "weapons": "Holding the legendary ancestral dragon-inscribed broadsword in ornate lacquer scabbard."
    },
    {
        "id": "tran_quoc_toan_16yo",
        "name_vn": "Hoài Văn Hầu Trần Quốc Toản (16 tuổi)",
        "role": "Thiếu niên anh hùng bóp nát quả cam, dấy cờ Phá Cường Địch Báo Hoàng Ân",
        "folder": "03_Dong_A_War_Heroes/tran_quoc_toan_16yo",
        "appearance": "16-year-old fiercely courageous Vietnamese noble youth, fiery eyes burning with patriotic resolve, muscular athletic teenage frame, hair tied in high thoan ke bun.",
        "costume": "Reinforced brown leather tunic over indigo linen shirt, dark linen trousers, barefoot, red silk headband.",
        "weapons": "Right fist clenched as if crushing an orange; holding a red silk battle flag with six gold characters 'Phá Cường Địch Báo Hoàng Ân'."
    },
    {
        "id": "tran_binh_trong_26yo",
        "name_vn": "Bảo Nghĩa Vương Trần Bình Trọng (26 tuổi)",
        "role": "Danh tướng thà làm quỷ nước Nam chứ không thèm làm vương đất Bắc",
        "folder": "03_Dong_A_War_Heroes/tran_binh_trong_26yo",
        "appearance": "26-year-old fearless heroic Vietnamese general, tall muscular bronze sun-baked physique, unyielding fierce eyes radiating supreme defiance, bleeding forehead battle scratch.",
        "costume": "Torn leather and iron lamellar vest revealing fierce Giao Long dragon tattoo across his chest, ripped dark combat trousers, barefoot.",
        "weapons": "Broken iron spear shaft held firmly in hand."
    },
    {
        "id": "yet_kieu_25yo",
        "name_vn": "Yết Kiêu (25 tuổi)",
        "role": "Gia nô trung nghĩa, đệ nhất thủy thần lặn nước đục thuyền giặc",
        "folder": "03_Dong_A_War_Heroes/yet_kieu_25yo",
        "appearance": "25-year-old legendary amphibious diver warrior, barefoot, powerful glistening tanned muscular body, intense focused hunter gaze.",
        "costume": "Dark blue linen loincloth, full-thigh intricate indigo sea-monster Giao Long tattoos wrapping around both legs and waist.",
        "weapons": "Holding a sharp forged-iron underwater auger drill tool and heavy aquatic broad knife."
    },
    {
        "id": "da_tuong_28yo",
        "name_vn": "Dã Tượng (28 tuổi)",
        "role": "Gia nô đại tướng, thống lĩnh tượng binh thần dũng",
        "folder": "03_Dong_A_War_Heroes/da_tuong_28yo",
        "appearance": "28-year-old giant muscular Vietnamese warrior, broad chest, towering build, rugged loyal bearded face, courageous fearless gaze.",
        "costume": "Heavy studded rawhide chest harness over coarse dark brown tunic, leather arm bracers, barefoot.",
        "weapons": "Holding a massive iron elephant hook (giao tuong) and heavy iron-spiked mace."
    },

    # 04. Nhóm Tướng lĩnh Nguyên Mông
    {
        "id": "thoat_hoan_toghan_35yo",
        "name_vn": "Trấn Nam Vương Thoát Hoan (35 tuổi)",
        "role": "Hoàng tử Mông Cổ, Tổng tư lệnh đạo quân viễn chinh xâm lược",
        "folder": "04_Mongol_Commanders/thoat_hoan_toghan_35yo",
        "appearance": "35-year-old bulky intimidating Mongol prince, broad flat weathered face, dark fierce eyes turning to paranoid dread, long black hair braided in traditional Mongol queue with shaven crown.",
        "costume": "Pointed fur-trimmed Mongol iron helmet with brass horsehair crest, heavy black iron scale armor over wolf-fur lined brocade caftan, leather archery thumb ring, heavy riding boots.",
        "weapons": "Curved recurve composite bow in leather bowcase and heavy Mongol saber."
    },
    {
        "id": "o_ma_nhi_omar_40yo",
        "name_vn": "Ô Mã Nhi (40 tuổi)",
        "role": "Thủy sư tướng quân Nguyên Mông, hung hãn tàn bạo trên sông Bạch Đằng",
        "folder": "04_Mongol_Commanders/o_ma_nhi_omar_40yo",
        "appearance": "40-year-old ferocious Central Asian Muslim naval commander in Mongol service, tall imposing stature, rugged tanned face with curly reddish-brown beard, predatory cruel eyes.",
        "costume": "Ornate iron-plated brigandine armor over dark woolen tunic, fur-lined pointed helmet, heavy leather gauntlets, riding boots.",
        "weapons": "Curved Persian-style steel scimitar with bone hilt."
    },

    # 05. Nhóm Thiền Phái Trúc Lâm & Hoàng Hôn Vương Triều
    {
        "id": "tran_nhan_tong_warrior_28yo",
        "name_vn": "Trần Nhân Tông - Thời chiến chinh (28 tuổi)",
        "role": "Vị vua anh hùng đánh bại quân Nguyên Mông lần 2 & 3",
        "folder": "05_Zen_Emperor_And_Later_Era/tran_nhan_tong_warrior_28yo",
        "appearance": "28-year-old handsome wise Vietnamese monarch, serene yet determined expression, compassionate intelligent eyes, neat trimmed mustache, high royal topknot.",
        "costume": "Pale gold silk imperial Giao Linh robe paired with practical lightweight boiled-leather arm guards and bronze-buckled waist sash, soft embroidered fabric boots.",
        "weapons": "Hand resting on an imperial dragon-engraved bronze ceremonial sword."
    },
    {
        "id": "tran_nhan_tong_zen_monk_48yo",
        "name_vn": "Phật Hoàng Trần Nhân Tông (48 tuổi)",
        "role": "Sơ tổ Thiền phái Trúc Lâm Yên Tử",
        "folder": "05_Zen_Emperor_And_Later_Era/tran_nhan_tong_zen_monk_48yo",
        "appearance": "48-year-old enlightened Vietnamese Zen master, clean shaven head, gentle benevolent smile, eyes radiating boundless tranquility and transcendent wisdom.",
        "costume": "Humble coarse cinnamon-brown Buddhist kasaya robe draped over simple grey linen inner gown, wooden prayer beads around wrist, simple woven straw sandals.",
        "weapons": "Holding a natural curved bamboo pilgrim staff."
    },
    {
        "id": "huyen_tran_cong_chua_19yo",
        "name_vn": "Công chúa Huyền Trân (19 tuổi)",
        "role": "Công chúa nhà Trần hòa thân Champa đổi lấy hai châu Ô Lý",
        "folder": "05_Zen_Emperor_And_Later_Era/huyen_tran_cong_chua_19yo",
        "appearance": "19-year-old graceful aristocratic Vietnamese royal princess, delicate melancholic features, deep sorrowful almond eyes carrying the heavy weight of national destiny, hair styled in royal court updo with pearl hairpins.",
        "costume": "Exquisite multi-layered lotus-pink and ivory silk Giao Linh robe, flowing translucent gauze mantle, embroidered phoenix sash with jade tassels, soft embroidered slippers.",
        "weapons": "Holding a delicately folded silk handkerchief."
    },
    {
        "id": "ho_quy_ly_60yo",
        "name_vn": "Hồ Quý Ly (60 tuổi)",
        "role": "Nhà cải cách kiệt xuất, quyền thần lập nên triều Hồ",
        "folder": "05_Zen_Emperor_And_Later_Era/ho_quy_ly_60yo",
        "appearance": "60-year-old shrewd visionary Vietnamese statesman, high intellectual forehead, deep-set calculating eyes hiding ruthless ambition, neatly groomed grey mustache, upright commanding posture.",
        "costume": "Dignified dark purple scholar-mandarin Giao Linh silk robe with silver thread embroidery, broad black silk waist sash with silver plaque, square scholar hat, black leather court shoes.",
        "weapons": "Holding a newly minted paper banknote (Thong Bao Hoi Sao)."
    }
]

def build_turnaround_master_json():
    turnaround_dict = {}
    for char in CHARACTER_DATA:
        cid = char["id"]
        char_desc = f"Character: {char['name_vn']} ({char['role']}). Appearance: {char['appearance']} Costume: {char['costume']} Weapons/Props: {char['weapons']}."
        full_prompt = f"{TURNAROUND_TEMPLATE_PREFIX} {char_desc} {TURNAROUND_TEMPLATE_SUFFIX}"
        
        turnaround_dict[cid] = {
            "character_id": cid,
            "character_name_vn": char["name_vn"],
            "role": char["role"],
            "asset_folder": f"04_Assets/characters/{char['folder']}",
            "turnaround_prompt_banana": full_prompt,
            "required_views": ["portrait", "profile", "front", "back"],
            "status": "PROMPT_READY_PENDING_RENDER"
        }
        
        # Ensure asset folder exists
        folder_path = BASE_DIR / "04_Assets" / "characters" / char["folder"]
        folder_path.mkdir(parents=True, exist_ok=True)
        
        # Write individual character spec markdown
        spec_md = folder_path / "README.md"
        with open(spec_md, "w", encoding="utf-8") as f:
            f.write(f"# TẠO HÌNH NHÂN VẬT: {char['name_vn'].upper()}\n")
            f.write(f"## {char['role']}\n\n")
            f.write(f"- **Mã định danh (ID)**: `{cid}`\n")
            f.write(f"- **Thư mục tài sản**: `04_Assets/characters/{char['folder']}/`\n")
            f.write(f"- **Trạng thái**: Chờ Render Master Sheet 1280x720 (`{cid}_turnaround_sheet_master.png`)\n\n")
            f.write("### 1. MÔ TẢ TẠO HÌNH & KHẢO CỔ HỌC\n")
            f.write(f"- **Diện mạo**: {char['appearance']}\n")
            f.write(f"- **Phục trang**: {char['costume']}\n")
            f.write(f"- **Đạo cụ/Vũ khí**: {char['weapons']}\n\n")
            f.write("### 2. PROMPT SINH CHARACTER TURNAROUND SHEET 4 GÓC NHÌN (GEMINI BANANA / FLUX.1 / IMAGEN 3)\n")
            f.write("```text\n")
            f.write(full_prompt + "\n")
            f.write("```\n\n")
            f.write("### 3. QUY TRÌNH TRÍCH XUẤT CROP GÓC NHÌN\n")
            f.write("Sau khi có file Master Sheet, chạy lệnh:\n")
            f.write(f"```bash\npython tools/manage_turnaround_sheets.py --crop {cid} --view portrait\n")
            f.write(f"python tools/manage_turnaround_sheets.py --crop {cid} --view front\n")
            f.write(f"python tools/manage_turnaround_sheets.py --crop {cid} --view profile\n")
            f.write(f"python tools/manage_turnaround_sheets.py --crop {cid} --view back\n```\n")

    OUTPUT_JSON.parent.mkdir(parents=True, exist_ok=True)
    with open(OUTPUT_JSON, "w", encoding="utf-8") as f:
        json.dump({
            "project": "Tran_Empire (Đông A Hùng Ký)",
            "specification": "FlowKit 4-View Character Turnaround Sheet",
            "total_characters": len(turnaround_dict),
            "characters": turnaround_dict
        }, f, ensure_ascii=False, indent=2)

    print(f"[✓] Đã tạo thành công {len(turnaround_dict)} Character Turnaround Prompts tại: {OUTPUT_JSON}")
    print(f"[✓] Đã khởi tạo cấu trúc thư mục tài sản cho {len(turnaround_dict)} nhân vật tại: {CHARACTERS_ASSETS_DIR}")

if __name__ == "__main__":
    build_turnaround_master_json()
