#!/usr/bin/env python3
"""
FreeExile Asset Safety and Integrity Quality Gate CLI.
Enforces the Zero-Blind-Deletion Protocol and verifies that Cocos Creator
resources bundle contains all required game assets with non-zero sizes.
"""

import sys
from pathlib import Path

REQUIRED_CATEGORIES = [
    "animations",
    "banners",
    "characters",
    "currencies",
    "environment",
    "loading",
    "map",
    "monsters",
    "portraits",
    "savage_vfx",
    "shop",
    "skills",
    "ui",
    "vfx",
    "vltk1",
    "weapons",
]

REQUIRED_UI_MODULES = [
    "combat",
    "ascendancy",
    "dialogue",
    "endgame_atlas",
    "guild",
    "meridian",
    "quests",
    "security",
    "stash",
    "agent_orb",
]

MIN_TOTAL_FILES = 300


def run_asset_safety_check() -> int:
    project_root = Path(__file__).resolve().parent.parent.parent
    resources_dir = project_root / "client" / "cocos" / "assets" / "resources"

    print("=" * 65)
    print("FREEEXILE ASSET SAFETY & INTEGRITY AUDIT")
    print("=" * 65)
    print(f"Target Resource Path: {resources_dir}")

    if not resources_dir.exists():
        print(f"[FAIL] Cocos resources directory does not exist: {resources_dir}")
        return 1

    errors = []

    # 1. Category checks
    for cat in REQUIRED_CATEGORIES:
        cat_path = resources_dir / cat
        if not cat_path.is_dir():
            errors.append(f"Missing required asset category: {cat}")

    # 2. UI submodules check
    ui_dir = resources_dir / "ui"
    if ui_dir.is_dir():
        for mod in REQUIRED_UI_MODULES:
            mod_path = ui_dir / mod
            if not mod_path.is_dir():
                errors.append(f"Missing required UI submodule: ui/{mod}")
    else:
        errors.append("Missing ui/ directory")

    # 3. File count and zero-byte check
    all_files = list(resources_dir.rglob("*.*"))
    file_count = len(all_files)
    print(f"Discovered Asset Files: {file_count}")

    if file_count < MIN_TOTAL_FILES:
        errors.append(
            f"Asset count ({file_count}) is below minimum threshold ({MIN_TOTAL_FILES})"
        )

    zero_byte_files = [f for f in all_files if f.stat().st_size == 0]
    if zero_byte_files:
        errors.append(f"Found {len(zero_byte_files)} zero-byte corrupted files")

    # 4. Summary report
    print("-" * 65)
    if errors:
        print(f"[FAILED] {len(errors)} asset safety violations detected:")
        for err in errors:
            print(f"  - {err}")
        print("=" * 65)
        return 1

    print("[PASS] All required asset categories and UI submodules verified.")
    print(f"[PASS] Asset bundle integrity confirmed ({file_count} files, 0 zero-byte).")
    print("=" * 65)
    return 0


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