# -*- coding: utf-8 -*-
"""
tools/manage_turnaround_sheets.py
Công cụ quản lý, kiểm toán và trích xuất góc nhìn từ hệ thống Character Turnaround Sheets
cho dự án Đông A Hùng Ký (Tran_Empire).
Hỗ trợ kiểm tra tiến độ, chuẩn hóa kích thước 720p (1280x720) và cắt góc nhìn độc lập (crop).
"""

import sys
import os
import argparse
from pathlib import Path
from PIL import Image

sys.stdout.reconfigure(encoding='utf-8')

BASE_DIR = Path(__file__).resolve().parent.parent
CHARACTERS_DIR = BASE_DIR / "04_Assets" / "characters"

# Cấu hình vùng crop tương đối trên tỷ lệ ảnh 16:9 (Left, Top, Right, Bottom)
# Layout chuẩn 4 khung ngang trên nền trắng studio:
# 1. Close-up Bust: x: 0% -> 28%
# 2. Side Profile: x: 28% -> 48%
# 3. Front View: x: 48% -> 74%
# 4. Back View: x: 74% -> 100%
CROP_BOXES = {
    "portrait": (0.0, 0.0, 0.28, 1.0),
    "profile": (0.28, 0.0, 0.48, 1.0),
    "front": (0.48, 0.0, 0.74, 1.0),
    "back": (0.74, 0.0, 1.0, 1.0),
}

def scan_turnaround_sheets():
    results = []
    if not CHARACTERS_DIR.exists():
        return results

    for root, dirs, files in os.walk(CHARACTERS_DIR):
        for f in files:
            if "turnaround_sheet" in f and f.endswith(".png"):
                full_path = Path(root) / f
                try:
                    rel_path = full_path.relative_to(CHARACTERS_DIR)
                except ValueError:
                    rel_path = full_path
                size_bytes = full_path.stat().st_size
                try:
                    with Image.open(full_path) as img:
                        w, h = img.size
                except Exception:
                    w, h = (0, 0)
                results.append({
                    "path": full_path,
                    "rel_path": str(rel_path),
                    "filename": f,
                    "folder": full_path.parent.name,
                    "size_bytes": size_bytes,
                    "dimensions": f"{w}x{h}",
                    "is_720p": (w == 1280 and h == 720),
                    "is_master": "master" in f
                })
    return results

def print_status():
    sheets = scan_turnaround_sheets()
    masters = [s for s in sheets if s["is_master"]]
    p720s = [s for s in sheets if s["is_720p"]]
    
    print("\n" + "=" * 80)
    print("🎨 BÁO CÁO HỆ THỐNG CHARACTER TURNAROUND SHEETS - ĐÔNG A HÙNG KÝ")
    print("=" * 80)
    print(f"Tổng số bản Master Turnaround đã có trên ổ cứng : {len(masters)}")
    print(f"Tổng số bản 720p Pipeline (1280x720) đã sẵn sàng : {len(p720s)}")
    print("-" * 80)
    if not sheets:
        print("[!] CẢNH BÁO: Chưa có tệp hình ảnh turnaround_sheet.png nào trong 04_Assets/characters/!")
        print("    Cần sử dụng các prompts từ 02_AI_Prompts/character_turnaround_sheets_master.json")
        print("    để sinh ảnh bằng Gemini Banana / FLUX.1 / Imagen 3.")
    else:
        print(f"{'Thư Mục Nhân Vật':<35} | {'Tên File':<30} | {'Độ Phân Giải'}")
        print("-" * 80)
        for s in sorted(sheets, key=lambda x: (x['folder'], x['filename'])):
            print(f"{s['folder']:<35} | {s['filename']:<30} | {s['dimensions']}")
    print("=" * 80 + "\n")

def crop_view(char_name, view_name, output_dir=None):
    sheets = scan_turnaround_sheets()
    target_sheet = None
    for s in sheets:
        if char_name.lower() in s["filename"].lower() and s["is_master"]:
            target_sheet = s
            break
            
    if not target_sheet:
        print(f"[!] Không tìm thấy bản master của nhân vật: {char_name}")
        return False
        
    if view_name not in CROP_BOXES:
        print(f"[!] Góc nhìn không hợp lệ: {view_name}. Cho phép: {list(CROP_BOXES.keys())}")
        return False
        
    img = Image.open(target_sheet["path"])
    w, h = img.size
    box = CROP_BOXES[view_name]
    crop_coords = (int(box[0] * w), int(box[1] * h), int(box[2] * w), int(box[3] * h))
    cropped = img.crop(crop_coords)
    
    if not output_dir:
        output_dir = target_sheet["path"].parent / "views"
    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)
    
    out_file = output_dir / f"{char_name}_{view_name}.png"
    cropped.save(out_file)
    print(f"[✓] Đã trích xuất góc nhìn [{view_name}] thành công: {out_file} ({cropped.size[0]}x{cropped.size[1]})")
    return True

def main():
    parser = argparse.ArgumentParser(description="Quản lý Character Turnaround Sheets - Tran_Empire")
    parser.add_argument("--status", action="store_true", help="Hiển thị báo cáo hiện trạng")
    parser.add_argument("--crop", type=str, help="Tên nhân vật cần trích xuất góc nhìn")
    parser.add_argument("--view", type=str, choices=["portrait", "profile", "front", "back"], help="Góc nhìn cần crop")
    args = parser.parse_args()
    
    if args.crop and args.view:
        crop_view(args.crop, args.view)
    else:
        print_status()

if __name__ == "__main__":
    main()
