"""
FreeExile: Migrate All Game Assets from Legacy WebApp to Cocos Creator Resources.
Copies all art, UI, character, monster, weapon, currency, map, and animation assets
into client/cocos/assets/resources/ for native Cocos Creator 3.x dynamic loading.
"""

import os
import shutil
import hashlib
from pathlib import Path


def get_file_hash(filepath: Path) -> str:
    h = hashlib.sha256()
    with open(filepath, "rb") as f:
        while chunk := f.read(65536):
            h.update(chunk)
    return h.hexdigest()


def migrate_assets():
    project_root = Path(__file__).resolve().parent.parent.parent
    src_dir = project_root / "client" / "webapp" / "assets"
    dst_dir = project_root / "client" / "cocos" / "assets" / "resources"

    if not src_dir.exists():
        raise FileNotFoundError(f"Source directory not found: {src_dir}")

    dst_dir.mkdir(parents=True, exist_ok=True)

    copied = 0
    identical = 0
    total_bytes = 0
    categories = {}

    for root, dirs, files in os.walk(src_dir):
        rel_root = Path(root).relative_to(src_dir)
        target_root = dst_dir / rel_root
        target_root.mkdir(parents=True, exist_ok=True)

        for filename in files:
            src_file = Path(root) / filename
            dst_file = target_root / filename

            category = rel_root.parts[0] if rel_root.parts else "root"
            categories[category] = categories.get(category, 0) + 1

            file_size = src_file.stat().st_size
            total_bytes += file_size

            if dst_file.exists():
                src_hash = get_file_hash(src_file)
                dst_hash = get_file_hash(dst_file)
                if src_hash == dst_hash:
                    identical += 1
                    continue

            shutil.copy2(src_file, dst_file)
            copied += 1

    print("=" * 60)
    print("COCOS ASSET MIGRATION REPORT")
    print("=" * 60)
    print(f"Source Directory      : {src_dir}")
    print(f"Destination Directory : {dst_dir}")
    print(f"Total Files Found     : {copied + identical}")
    print(f"Newly Copied          : {copied}")
    print(f"Already Identical     : {identical}")
    print(f"Total Asset Volume    : {total_bytes / (1024 * 1024):.2f} MB")
    print("-" * 60)
    print("Breakdown by Category :")
    for cat, count in sorted(categories.items()):
        print(f"  - {cat:20s}: {count:3d} files")
    print("=" * 60)
    print("MIGRATION COMPLETED SUCCESSFULLY!")


if __name__ == "__main__":
    migrate_assets()
