#!/usr/bin/env python3
"""
apply_corp_translations.py — Overlay Hungarian text on High Orbit corporation card PNGs.

Corporation cards are stored in portrait orientation (822×1122) but designed as landscape.
Workflow: rotate 90° CCW → apply overlays in landscape space (1122×822) → rotate 90° CW → save.

Usage:
    python apply_corp_translations.py
    python apply_corp_translations.py --test    # saves to output/corps/test/
    python apply_corp_translations.py --card "Lagrange Collective"
"""

import json
import os
import sys
import argparse
from PIL import Image, ImageDraw, ImageFont

# ---------------------------------------------------------------------------
# Paths
# ---------------------------------------------------------------------------
BASE_DIR   = r"C:\progik\forditsunk"
SOURCE_DIR = os.path.join(BASE_DIR, r"source\High_Orbit\High Orbit\High_Orbit_Professional_Print_Cards_3_1")
OUTPUT_DIR = os.path.join(BASE_DIR, "output", "corps")
CORPS_FILE = os.path.join(BASE_DIR, "translations", "corps.json")
FONTS_DIR  = r"C:\Windows\Fonts"

FONT_NAME   = os.path.join(FONTS_DIR, "arialbd.ttf")    # corp name — bold
FONT_BODY   = os.path.join(FONTS_DIR, "calibri.ttf")    # body text
FONT_FLAVOR = os.path.join(FONTS_DIR, "georgiaz.ttf")   # flavor (bold italic)

# ---------------------------------------------------------------------------
# In rotated landscape space (1122 × 822 px)
# Corp layout:
#   CORPORATION banner:  y≈20–58  (keep; not translated)
#   Corp name:           y≈60–295, x≈280–940
#   Start icons:         y≈290–420, x≈15–210   (keep icons)
#   Start description:   y≈415–615, x≈15–265
#   EFFECT/ACTION box:   y≈240–685, x≈275–945  (keep box & icons; translate text only)
#   Flavor strip:        y≈695–740, x≈15–945
# ---------------------------------------------------------------------------

# Font sizes
SZ_NAME   = 58   # px — large corp name
SZ_BODY   = 19
SZ_FLAVOR = 19

COLOR_NAME  = (180, 20, 20)     # deep red — matches original style
COLOR_DARK  = (25, 25, 25)
BG_CARD     = (200, 200, 200)   # card background (silver-gray)
BG_EFFECT   = (240, 240, 240)   # inside the white effect box
BG_FLAVOR   = (200, 200, 200)


def load_font(path, size):
    try:
        return ImageFont.truetype(path, size)
    except Exception as e:
        print(f"  Warning: {e}")
        return ImageFont.load_default()


def wrap_to_lines(text, font, max_px, draw):
    words = text.split()
    lines, current = [], []
    for word in words:
        test = " ".join(current + [word])
        bb = draw.textbbox((0, 0), test, font=font)
        if bb[2] <= max_px:
            current.append(word)
        else:
            if current:
                lines.append(" ".join(current))
            current = [word]
    if current:
        lines.append(" ".join(current))
    return lines


def draw_region(img, region, paragraphs, font, bg, color,
                halign="center", valign="center", pad_x=10, pad_y=6, gap=3):
    x1, y1, x2, y2 = region
    draw = ImageDraw.Draw(img)
    draw.rectangle([x1, y1, x2, y2], fill=bg)

    max_w = x2 - x1 - 2 * pad_x
    bb = draw.textbbox((0, 0), "Ag", font=font)
    line_h = (bb[3] - bb[1]) + gap

    all_lines = []
    for i, para in enumerate(paragraphs):
        # Support explicit \n within a paragraph
        for sub in para.split("\n"):
            all_lines.extend(wrap_to_lines(sub, font, max_w, draw) if sub else [""])
        if i < len(paragraphs) - 1:
            all_lines.append("")

    total_h = len(all_lines) * line_h
    region_h = y2 - y1 - 2 * pad_y
    y = y1 + pad_y + (max(0, region_h - total_h) // 2 if valign == "center" else 0)

    for line in all_lines:
        if not line:
            y += line_h
            continue
        bb2 = draw.textbbox((0, 0), line, font=font)
        tw = bb2[2] - bb2[0]
        x = x1 + ((x2 - x1 - tw) // 2 if halign == "center" else pad_x)
        draw.text((x, y), line, font=font, fill=color)
        y += line_h


# ---------------------------------------------------------------------------
# Corporation translations — loaded from translations/corps.json
# Coordinates are in ROTATED landscape space (1122 × 822)
# ---------------------------------------------------------------------------

CORPS = json.load(open(CORPS_FILE, encoding='utf-8'))


def process_corp(key, data, out_dir):
    src = os.path.join(SOURCE_DIR, data["file"])
    if not os.path.exists(src):
        print(f"  [WARN] Not found: {src}")
        return False

    fn_name   = load_font(FONT_NAME,   SZ_NAME)
    fn_body   = load_font(FONT_BODY,   SZ_BODY)
    fn_flavor = load_font(FONT_FLAVOR, SZ_FLAVOR)

    # Load and rotate to landscape
    img = Image.open(src).convert("RGBA")
    img = img.rotate(90, expand=True)   # 90° CCW → landscape 1122×822

    # Corp name
    draw_region(img, data["name_region"], [data["name"]],
                fn_name, BG_CARD, COLOR_NAME, halign="center", valign="center")

    # Starting description
    draw_region(img, data["start_region"], data["start_text"],
                fn_body, BG_CARD, COLOR_DARK, halign="left", valign="top", pad_y=4)

    # Effect text
    draw_region(img, data["effect_region"], data["effect"],
                fn_body, BG_EFFECT, COLOR_DARK, halign="center", valign="center")

    # Action text (if present)
    if data.get("action"):
        draw_region(img, data["action_region"], data["action"],
                    fn_body, BG_EFFECT, COLOR_DARK, halign="center", valign="center")

    # Flavor text
    draw_region(img, data["flavor_region"], [data["flavor"]],
                fn_flavor, BG_FLAVOR, COLOR_DARK, halign="center", valign="center")

    # Rotate back to portrait
    img = img.rotate(-90, expand=True)   # 90° CW → portrait 822×1122

    out_path = os.path.join(out_dir, data["file"])
    img.save(out_path, "PNG")
    return True


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--test", action="store_true")
    parser.add_argument("--card", type=str, default=None)
    args = parser.parse_args()

    out_dir = os.path.join(OUTPUT_DIR, "test") if args.test else OUTPUT_DIR
    os.makedirs(out_dir, exist_ok=True)

    to_process = CORPS
    if args.card:
        matches = {k: v for k, v in CORPS.items() if k.lower() == args.card.lower()}
        if not matches:
            print(f"Card '{args.card}' not found. Options: {list(CORPS.keys())}")
            sys.exit(1)
        to_process = matches

    total = 0
    for key, data in to_process.items():
        print(f"Processing: {key}...")
        ok = process_corp(key, data, out_dir)
        if ok:
            print(f"  -> saved {data['file']}")
            total += 1

    print(f"\nDone. {total} corporation card(s) saved to: {out_dir}")


if __name__ == "__main__":
    main()
