# -*- 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.
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"
TURNAROUND_DIR = CHARACTERS_DIR

# 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:
# 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 = []
    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
                rel_path = full_path.relative_to(CHARACTERS_DIR)
                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": f"{full_path.parent.parent.name}/{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" + "=" * 75)
    print("🎨 BÁO CÁO HỆ THỐNG CHARACTER TURNAROUND SHEETS - THẬP NGŨ NIÊN")
    print("=" * 75)
    print(f"Tổng số bản Master Turnaround đã hoàn thành : {len(masters)}")
    print(f"Tổng số bản 720p Pipeline (1280x720) đã sẵn sàng : {len(p720s)}")
    print("-" * 75)
    print(f"{'Nhóm Nhân Vật':<32} | {'Tên File':<35} | {'Độ Phân Giải'}")
    print("-" * 75)
    for s in sorted(sheets, key=lambda x: (x['folder'], x['filename'])):
        print(f"{s['folder']:<32} | {s['filename']:<35} | {s['dimensions']}")
    print("=" * 75 + "\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 crop_all_views(views=None):
    if views is None:
        views = ["portrait", "front"]
    sheets = scan_turnaround_sheets()
    masters = [s for s in sheets if s["is_master"]]
    print(f"\n🚀 Bắt đầu trích xuất hàng loạt ({views}) cho {len(masters)} nhân vật...")
    success_count = 0
    for s in masters:
        char_name = s["path"].parent.name
        for v in views:
            if crop_view(char_name, v):
                success_count += 1
    print(f"\n[✓] Hoàn thành trích xuất hàng loạt! Tổng số góc nhìn đã tạo: {success_count}")
    return success_count

def main():
    parser = argparse.ArgumentParser(description="Quản lý Character Turnaround Sheets")
    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")
    parser.add_argument("--crop-all", action="store_true", help="Trích xuất tự động portrait và front cho toàn bộ nhân vật")
    
    args = parser.parse_args()
    if args.crop_all:
        crop_all_views()
    elif args.status or len(sys.argv) == 1:
        print_status()
    elif args.crop and args.view:
        crop_view(args.crop, args.view)
    else:
        parser.print_help()

if __name__ == "__main__":
    main()
