#!/usr/bin/env python3
"""
card_clean.py — Remove English text from High Orbit Infrastructure project cards.

Produces clean PNGs with text inpainted out but gradient backgrounds intact.
These become the base images for the Hungarian text overlay (step 3).

IMPORTANT: Do NOT run on all cards until user approves the output on one card
type first.  Run on a single type with --card to get approval first.

Usage:
    python scripts/card_clean.py --card "Orbital Headquarters"   # test one type
    python scripts/card_clean.py --card "Orbital Headquarters" --test
    python scripts/card_clean.py   # all types (only after approval)

Output: output/cards/clean/<filename>.png
"""

import os
import sys
import glob
import argparse
import numpy as np
from PIL import Image
import importlib.util as _ilu

# ---------------------------------------------------------------------------
# Paths
# ---------------------------------------------------------------------------
BASE_DIR   = r"C:\progik\forditsunk"
SOURCE_DIR = os.path.join(BASE_DIR, r"source\High_Orbit\High Orbit")
OUTPUT_DIR = os.path.join(BASE_DIR, "output", "cards")

# ---------------------------------------------------------------------------
# Load gradient_fill module
# ---------------------------------------------------------------------------
_gf_path = os.path.join(os.path.dirname(__file__), "gradient_fill.py")
_spec = _ilu.spec_from_file_location("gradient_fill", _gf_path)
_gf = _ilu.module_from_spec(_spec)
_spec.loader.exec_module(_gf)
inpaint_body_text = _gf.inpaint_body_text

# ---------------------------------------------------------------------------
# Card geometry — portrait orientation, 822 × 1122 px
# ---------------------------------------------------------------------------
REGION_TITLE     = (92,  188, 730, 227)   # title band
REGION_RESTRICT  = (92,  242, 480, 267)   # restriction line (Orbital HQ only)
REGION_EFFECT    = (92,  342, 730, 478)   # effect / action text
REGION_FLAVOR    = (92,  904, 730, 1022)  # flavor strip — standard
REGION_FLAVOR_VP = (92,  904, 618, 1022)  # flavor strip — VP cards (narrower)

# Card types with a VP icon on the right edge of the flavor strip
VP_CARDS = {"Space Habitat", "Planetary Outpost", "Probe", "Observatory"}

# Card types with a restriction line
RESTRICTED_CARDS = {"Orbital Headquarters"}

# All 17 card types in this expansion
ALL_CARD_TYPES = [
    "Orbital Headquarters", "Space Habitat",    "Planetary Outpost",
    "Powersat",             "Salvage Depot",     "Hydroponics",
    "Weather Satellite",    "Comsat",            "Navigational Beacon",
    "Orbital Shipyard",     "Freighter",         "Asteroid Mine",
    "Auto Factory",         "Propellent Depot",  "Probe",
    "Science Facility",     "Observatory",
]


# ---------------------------------------------------------------------------
# Core function
# ---------------------------------------------------------------------------

def clean_card(src_path, out_path, card_type, verbose=True):
    """
    Inpaint all text regions on a single card PNG.
    card_type: determines which regions to inpaint.
    """
    img = Image.open(src_path).convert("RGB")
    arr = np.array(img)
    h, w = arr.shape[:2]
    if (w, h) != (822, 1122) and verbose:
        print(f"  [WARN] Unexpected size {w}x{h}, expected 822x1122")

    # Title
    arr = inpaint_body_text(arr, *REGION_TITLE, radius=8)

    # Restriction (Orbital HQ only)
    if card_type in RESTRICTED_CARDS:
        arr = inpaint_body_text(arr, *REGION_RESTRICT, radius=6)

    # Effect / action body
    arr = inpaint_body_text(arr, *REGION_EFFECT, radius=10)

    # Flavor — narrower for VP cards
    flavor_region = REGION_FLAVOR_VP if card_type in VP_CARDS else REGION_FLAVOR
    arr = inpaint_body_text(arr, *flavor_region, radius=8)

    img_out = Image.fromarray(arr, "RGB")
    os.makedirs(os.path.dirname(out_path), exist_ok=True)
    img_out.save(out_path, "PNG")
    if verbose:
        print(f"    saved -> {out_path}")
    return True


def find_source_files(card_type):
    """Find all source PNGs for a card type, deduplicated by filename."""
    pattern = os.path.join(SOURCE_DIR, "**", f"*{card_type}*.png")
    all_files = sorted(glob.glob(pattern, recursive=True))
    seen, unique = set(), []
    for f in all_files:
        name = os.path.basename(f)
        if name not in seen:
            seen.add(name)
            unique.append(f)
    return unique


def main():
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--card", default=None,
                    help="Card type name (partial match). E.g. 'Orbital Headquarters'")
    ap.add_argument("--test", action="store_true",
                    help="Save to output/cards/clean/test/ instead")
    ap.add_argument("--quiet", action="store_true")
    args = ap.parse_args()

    verbose = not args.quiet
    clean_dir = os.path.join(OUTPUT_DIR, "clean")
    if args.test:
        clean_dir = os.path.join(OUTPUT_DIR, "clean", "test")

    types_to_process = ALL_CARD_TYPES
    if args.card:
        needle = args.card.lower()
        types_to_process = [t for t in ALL_CARD_TYPES if needle in t.lower()]
        if not types_to_process:
            print(f"No card type matching '{args.card}'. Available:\n  " +
                  "\n  ".join(ALL_CARD_TYPES))
            sys.exit(1)

    total = 0
    for ct in types_to_process:
        sources = find_source_files(ct)
        if not sources:
            if verbose:
                print(f"[WARN] No source files found for: {ct}")
            continue
        if verbose:
            print(f"Processing '{ct}' ({len(sources)} files)...")
        for src in sources:
            name = os.path.basename(src)
            out = os.path.join(clean_dir, name)
            if clean_card(src, out, ct, verbose=verbose):
                total += 1

    print(f"\nDone. {total} card(s) cleaned -> {clean_dir}")


if __name__ == "__main__":
    main()
