#!/usr/bin/env python3
"""
Create app icons (PNG) of multiple sizes (16/32/48/128) from a source transparent PNG.

Usage:
  python3 make_icons_from_png.py input.png
  python3 make_icons_from_png.py input.png --sizes 16,32,48,128 --prefix icon

Behavior:
  - Preserves transparency (RGBA).
  - Fits the image into a square canvas of target size while preserving aspect ratio.
  - Centers the image on a transparent background if the source is not square.
  - Outputs files named like <prefix><size>.png in the same directory as the script
    (icons/icon16.png, icons/icon32.png, ... by default).
"""

from __future__ import annotations

import argparse
from pathlib import Path
from typing import Iterable, List

try:
    from PIL import Image  # type: ignore
except Exception:
    raise SystemExit("Pillow is required. Install with: pip install --upgrade pillow")


def parse_sizes(s: str) -> List[int]:
    out: List[int] = []
    for part in s.split(','):
        part = part.strip()
        if not part:
            continue
        try:
            v = int(part)
            if v <= 0:
                raise ValueError
            out.append(v)
        except Exception:
            raise SystemExit(f"Invalid size in --sizes: {part}")
    if not out:
        raise SystemExit("--sizes produced an empty list")
    return sorted(set(out))


def fit_to_square(img: Image.Image, size: int) -> Image.Image:
    # Ensure RGBA
    if img.mode != 'RGBA':
        img = img.convert('RGBA')
    # Scale preserving aspect ratio so the longest side == size
    w, h = img.size
    if w == 0 or h == 0:
        raise ValueError("Input image has invalid dimensions")
    scale = size / max(w, h)
    new_w = max(1, int(round(w * scale)))
    new_h = max(1, int(round(h * scale)))
    resized = img.resize((new_w, new_h), Image.Resampling.LANCZOS)
    # Create transparent square canvas and center paste
    canvas = Image.new('RGBA', (size, size), (0, 0, 0, 0))
    off_x = (size - new_w) // 2
    off_y = (size - new_h) // 2
    canvas.paste(resized, (off_x, off_y), resized)
    return canvas


def make_icons(src_path: Path, out_dir: Path, sizes: Iterable[int], prefix: str) -> None:
    with Image.open(src_path) as im:
        im.load()
        for s in sizes:
            out = fit_to_square(im, s)
            out_name = f"{prefix}{s}.png"
            out_path = out_dir / out_name
            out.save(out_path, format='PNG')
            print(f"[OK] {src_path.name} -> {out_name}")


def main() -> int:
    ap = argparse.ArgumentParser(description="Create icon PNGs (16/32/48/128) from a source PNG")
    ap.add_argument('input', help='Source transparent PNG')
    ap.add_argument('--sizes', default='16,32,48,128', help='Comma-separated sizes (default: 16,32,48,128)')
    ap.add_argument('--prefix', default='icon', help='Output filename prefix (default: icon)')
    args = ap.parse_args()

    src = Path(args.input)
    if not src.exists():
        print(f"[ERROR] Input not found: {src}")
        return 2
    sizes = parse_sizes(args.sizes)
    out_dir = Path(__file__).resolve().parent
    make_icons(src, out_dir, sizes, args.prefix)
    print("[DONE]")
    return 0


if __name__ == '__main__':
    raise SystemExit(main())

