#!/usr/bin/env python3
"""Downsizes res/img/*.jpeg into watch/resources/img/*.png for Pebble.

The 22 Major Arcana JPEGs in res/img/ are ~1MB/~1086x1810px each -
suitable for the desktop HTML reading (an <img> tag pointed at the file
as-is) but far too large for a Pebble app's own resource budget. This
script resizes each to CARD_WIDTH px wide (preserving aspect ratio) and
writes a PNG per card, named after tarot_data.c's own k_card_slug table
so watch/package.json's "resources.media" entries (IMG_CARD_<SLUG
UPPERCASE>, file img/<slug>.png) line up without a separate mapping
table anywhere.

CARD_WIDTH=72 (-> 72x120) is a hardware-verified ceiling, not a design
choice: full-display-width images (144-260px depending on platform) were
tried first and reliably crash real hardware with "PNG memory allocation
failed" - a runtime PNG-decoder memory constraint independent of the
app's own heap budget (lazy-loading only one image at a time didn't help
either). 72px is the size the original per-card screens used
successfully all session before that experiment.

Generated output, like i18n_tables.auto.c - not committed (see
.gitignore), regenerate by running this script directly or via the root
Makefile's `make watchapp` (task/target that also runs `pebble build`).
Requires Pillow (`pip install Pillow`), not part of this repo's own
desktop build/test toolchain.
"""
import os
import sys

from PIL import Image

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
SRC_DIR = os.path.normpath(os.path.join(SCRIPT_DIR, "..", "..", "res", "img"))
OUT_DIR = os.path.normpath(os.path.join(SCRIPT_DIR, "..", "resources", "img"))

CARD_WIDTH = 72

# (source file in res/img/, slug matching engine/src/tarot_data.c's
# k_card_slug table) - in TarotCard enum order (CARD_FOOL = 0 ... CARD_WORLD).
CARDS = [
    ("RWS_Tarot_00_Fool.jpeg", "fool"),
    ("RWS_Tarot_01_Magician.jpeg", "magician"),
    ("RWS_Tarot_02_High_Priestess.jpeg", "high_priestess"),
    ("RWS_Tarot_03_Empress.jpeg", "empress"),
    ("RWS_Tarot_04_Emperor.jpeg", "emperor"),
    ("RWS_Tarot_05_Hierophant.jpeg", "hierophant"),
    ("RWS_Tarot_06_Lovers.jpeg", "lovers"),
    ("RWS_Tarot_07_Chariot.jpeg", "chariot"),
    ("RWS_Tarot_08_Strength.jpeg", "strength"),
    ("RWS_Tarot_09_Hermit.jpeg", "hermit"),
    ("RWS_Tarot_10_Wheel_of_Fortune.jpeg", "wheel_of_fortune"),
    ("RWS_Tarot_11_Justice.jpeg", "justice"),
    ("RWS_Tarot_12_Hanged_Man.jpeg", "hanged_man"),
    ("RWS_Tarot_13_Death.jpeg", "death"),
    ("RWS_Tarot_14_Temperance.jpeg", "temperance"),
    ("RWS_Tarot_15_Devil.jpeg", "devil"),
    ("RWS_Tarot_16_Tower.jpeg", "tower"),
    ("RWS_Tarot_17_Star.jpeg", "star"),
    ("RWS_Tarot_18_Moon.jpeg", "moon"),
    ("RWS_Tarot_19_Sun.jpeg", "sun"),
    ("RWS_Tarot_20_Judgement.jpeg", "judgement"),
    ("RWS_Tarot_21_World.jpeg", "world"),
]


def main():
    os.makedirs(OUT_DIR, exist_ok=True)
    written = 0
    for src_name, slug in CARDS:
        src_path = os.path.join(SRC_DIR, src_name)
        out_path = os.path.join(OUT_DIR, f"{slug}.png")

        # wscript runs this on every `pebble build` (like gen_i18n_tables.py)
        # so a full 22-image resize must be cheap on the common no-op case -
        # skip any card whose output is already newer than its source JPEG.
        if os.path.exists(out_path) and os.path.getmtime(out_path) >= os.path.getmtime(src_path):
            continue

        with Image.open(src_path) as img:
            ratio = CARD_WIDTH / img.width
            height = round(img.height * ratio)
            resized = img.convert("RGB").resize((CARD_WIDTH, height), Image.LANCZOS)
            resized.save(out_path, "PNG", optimize=True)
        written += 1

    print(f"wrote {written}/{len(CARDS)} card images to {OUT_DIR}", file=sys.stderr)


if __name__ == "__main__":
    main()
