#!/usr/bin/env python3
"""
optimize-images.py — Generate responsive WebP variants of the site images.

For every source image it writes, next to the original, one WebP per target
width:  images/heros/contact_hero.png  →  images/heros/contact_hero-828.webp,
contact_hero-1280.webp, contact_hero-1920.webp ...

Originals are never modified. Blade picks the variants up automatically through
responsive_image() (app/Helpers/helpers.php): src = largest variant, srcset = all
of them. A width larger than the source is capped to the source width.

Usage:
  python3 scripts/optimize-images.py                  All presets below
  python3 scripts/optimize-images.py heros values     Selected presets
  python3 scripts/optimize-images.py --force          Rebuild existing variants
  python3 scripts/optimize-images.py --widths 480,960 public/images/foo.png ...

Re-run it after adding or replacing an image covered by a preset.
Requirements: Python 3 + Pillow with WebP support (pip install Pillow).
"""

import argparse
import glob
import os
import sys

from PIL import Image

PUBLIC = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'public')

# preset name → (glob patterns relative to public/, target widths, WebP quality)
PRESETS = {
    # Full-width heroes and posters (LCP elements): phone, laptop, desktop
    'heros': (['images/heros/*.webp', 'images/heros/*.png', 'images/heros/*.jpg'], [828, 1280, 1920], 78),
    # Mega-menu / related-products thumbnails, displayed at 80×80 CSS px
    'thumbs': (['images/heros/*.webp', 'images/heros/*.png', 'images/menu/*.webp'], [160], 80),
    # Content images in cards (image-block): grids of 2 to 5 columns
    'values': ([
        'images/our_team.webp', 'images/strong_relation.webp', 'images/values/*.webp',
        'images/innovation.webp', 'images/team_eco.png',
        'images/by_pass.webp', 'images/incendie.webp', 'images/optimisation.webp',
        'images/solutions/*.webp', 'images/product/*.webp', 'images/product/*.png', 'images/product/*.jpg',
        'images/solutions/*/*.webp', 'images/solutions/*/*.png', 'images/solutions/*/*.jpg',
    ], [480, 960], 78),
    # Partner logos, displayed at most 170×130 CSS px
    'logos': (['images/collaborators/*.png', 'images/collaborators/*.PNG', 'images/collaborators/*.jpg'], [340], 85),
}

VARIANT_SUFFIX = '-{}.webp'
# Smaller numeric suffixes are regular file names (e.g. "citeo-2.webp"), not variants
MIN_VARIANT_WIDTH = 64


def is_variant(path):
    stem = os.path.splitext(os.path.basename(path))[0]
    tail = stem.rsplit('-', 1)[-1]
    return path.endswith('.webp') and tail.isdigit() and int(tail) >= MIN_VARIANT_WIDTH


def build_variants(src, widths, quality, force=False):
    base = os.path.splitext(src)[0]
    written = []
    with Image.open(src) as im:
        im.load()
        has_alpha = im.mode in ('RGBA', 'LA') or (im.mode == 'P' and 'transparency' in im.info)
        im = im.convert('RGBA' if has_alpha else 'RGB')
        for width in sorted(set(min(w, im.width) for w in widths)):
            out = base + VARIANT_SUFFIX.format(width)
            if os.path.exists(out) and not force:
                continue
            height = round(im.height * width / im.width)
            resized = im if width == im.width else im.resize((width, height), Image.LANCZOS)
            resized.save(out, 'WEBP', quality=quality, method=6)
            # A variant must save at least 10%: otherwise the original is the better choice
            if os.path.getsize(out) > 0.9 * os.path.getsize(src):
                os.remove(out)
                continue
            written.append((out, os.path.getsize(out)))
    return written


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('targets', nargs='*', help='preset names or image paths')
    parser.add_argument('--widths', help='comma-separated widths, for explicit image paths')
    parser.add_argument('--quality', type=int, default=78)
    parser.add_argument('--force', action='store_true', help='rebuild variants that already exist')
    args = parser.parse_args()

    jobs = []  # (src, widths, quality)
    targets = args.targets or list(PRESETS)
    for target in targets:
        if target in PRESETS:
            patterns, widths, quality = PRESETS[target]
            for pattern in patterns:
                for src in sorted(glob.glob(os.path.join(PUBLIC, pattern))):
                    if not is_variant(src):
                        jobs.append((src, widths, quality))
        elif os.path.isfile(target):
            if not args.widths:
                sys.exit(f'--widths is required for explicit paths ({target})')
            jobs.append((target, [int(w) for w in args.widths.split(',')], args.quality))
        else:
            sys.exit(f'Unknown preset or file: {target}')

    for src, widths, quality in jobs:
        for out, size in build_variants(src, widths, quality, args.force):
            print(f'{os.path.getsize(src) // 1024:>6} KB → {size // 1024:>5} KB  {os.path.relpath(out, PUBLIC)}')

    print(f'{len(jobs)} source images checked.')


if __name__ == '__main__':
    main()
