#!/usr/bin/env python3
"""
AzerothAngler Media Extractor  —  run from the Media/ directory or from anywhere.

Usage:
    python extract.py                          # re-extract all sheet-sourced assets
    python extract.py "new_sheet.png"          # use a different sheet file

Assets marked "external: true" in sheet_crops.json were supplied as individual
files and are NOT re-extracted by this script. Drop replacements directly into
the generated/ folder with the correct filename.

Sheet-sourced assets (safe to re-extract):
    rune_disc, hook_ice_large, hook_ice_glowing, ui_sliders

External / individually supplied:
    logo_primary, banner_wide, emblem_round, portrait_square,
    rod_hook_large, rod_small, app_icon_face, app_icon_hook,
    hook_disc, tuskarr_standing
"""
import json, sys, os
from PIL import Image

HERE       = os.path.dirname(os.path.abspath(__file__))
CROPS_JSON = os.path.join(HERE, "sheet_crops.json")
GEN_DIR    = os.path.join(HERE, "generated")

def main():
    with open(CROPS_JSON) as f:
        config = json.load(f)

    sheet_name = sys.argv[1] if len(sys.argv) > 1 else config.get("source_name", "Azeroth Angler Media sheet.png")
    sheet_path = sheet_name if os.path.isabs(sheet_name) else os.path.join(HERE, sheet_name)

    if not os.path.exists(sheet_path):
        print(f"ERROR: Sheet not found: {sheet_path}")
        sys.exit(1)

    sheet = Image.open(sheet_path).convert("RGBA")
    os.makedirs(GEN_DIR, exist_ok=True)
    print(f"Source: {sheet_path}  ({sheet.width}×{sheet.height})")
    print(f"Output: {GEN_DIR}/\n")

    skipped, extracted, errors = [], [], []
    for asset in config["assets"]:
        name = asset["name"]
        fmt  = asset.get("format", "png")
        out  = os.path.join(GEN_DIR, f"{name}.{fmt}")

        if asset.get("external"):
            skipped.append(name)
            continue

        box = tuple(asset["box"])
        if box[2] > sheet.width or box[3] > sheet.height or box[2] <= box[0] or box[3] <= box[1]:
            errors.append(f"  ✗ {name}: bad box {box}")
            continue

        crop = sheet.crop(box)
        crop.save(out, "PNG", optimize=True)
        extracted.append(f"  ✓ {name}.{fmt}  {crop.width}×{crop.height}px")

    for line in extracted: print(line)
    if skipped:
        print(f"\nSkipped (external, not from sheet): {', '.join(skipped)}")
    if errors:
        print("\nERRORS:")
        for e in errors: print(e)
    print(f"\nDone — {len(extracted)} extracted, {len(skipped)} skipped.")

if __name__ == "__main__":
    main()
