"""
One-shot image processing pipeline for TCA Industries photo library.

Reads the curated mapping below, converts each JPG in /public/images/ to WebP,
places it in the right /public/images/<folder>/ subfolder, deletes the source JPG
only after the WebP is confirmed written, and prints a CSV-style report to stdout
with one row per processed image so IMAGES_REPORT.md can be assembled.

Run from project root:  python scripts/process_images.py
"""
from __future__ import annotations

import os
import sys
from pathlib import Path
from PIL import Image

ROOT = Path(__file__).resolve().parent.parent
IMG_DIR = ROOT / "public" / "images"

# (original_basename, new_basename_without_ext, target_subfolder, subject_description)
# subfolders: hero, atelier, showroom, services, products, team
MAPPING: list[tuple[str, str, str, str]] = [
    # ---- HERO candidates (6) ----
    ("0010", "hero-roulements-aiguilles-empiles-tca", "hero",
     "Stacked tapered needle roller bearings forming a Christmas-tree silhouette — strong artistic shot for homepage hero"),
    ("0030", "hero-moteur-electrique-bleu-weg-tca", "hero",
     "Bright blue WEG electric motor in close-up — vivid color, signature TCA subject"),
    ("0052", "hero-cartes-visite-tca-atelier-tca", "hero",
     "TCA business cards fanned out between toothed sprockets — strongly branded composition"),
    ("0220", "hero-technicien-reparation-moteur-electrique-tca", "hero",
     "Technician hands in gloves intervening on a blue electric motor terminal box — premium service hero"),
    ("0362", "hero-stator-bobinage-moteur-electrique-tca", "hero",
     "Symmetrical front view of an electric motor stator with copper windings, B&W — perfect rebobinage hero"),
    ("0502", "hero-stator-bobine-test-electrique-tca", "hero",
     "Stator with colored windings being electrically tested in workshop — rebobinage / diagnostic hero"),

    # ---- ELECTRIC MOTORS (sale / products) ----
    ("0002", "moteur-electrique-weg-bleu-vue-laterale-tca", "products",
     "WEG blue industrial electric motor, side view with nameplate"),
    ("0028", "moteur-electrique-bleu-detail-ailette-tca", "products",
     "Close-up of blue electric motor cooling fins and nameplate"),
    ("0303", "moteur-electrique-frein-detail-tca", "products",
     "Detail of a brake motor end with cooling fins"),

    # ---- BEARINGS / ROULEMENTS (products + services) ----
    ("0003", "roulement-bille-detail-macro-tca", "products",
     "Macro close-up of a deep-groove ball bearing"),
    ("0004", "roulement-bille-6319-detail-tca", "products",
     "Side view of SKF/FAG style 6319 ball bearing with reference visible"),
    ("0008", "roulement-bille-6319-perspective-tca", "products",
     "Ball bearing 6319 in 3/4 perspective on workbench"),
    ("0013", "roulement-aiguilles-empiles-cone-tca", "products",
     "Tapered roller bearings stacked into a cone with sprocket on top"),
    ("0015", "roulement-aiguilles-detail-tete-tca", "products",
     "Vertical close-up of stacked needle bearings with sprocket head"),
    ("0019", "roulement-pignon-laiton-detail-tca", "products",
     "Brass-colored small sprocket atop a roller bearing — abstract detail"),
    ("0044", "roulement-bille-6319-atelier-tca", "products",
     "Ball bearing 6319 photographed in the workshop with diffuse light"),

    # ---- BEARING BOX PACKAGING (products / showroom) ----
    ("0035", "stock-roulements-fag-rouge-rayonnage-tca", "showroom",
     "FAG-branded red bearing boxes on shop rack"),
    ("0039", "stock-roulements-skf-fag-rayonnage-tca", "showroom",
     "Tilted rack of red SKF and FAG bearing boxes"),
    ("0040", "stock-roulements-fag-detail-cartons-tca", "showroom",
     "Detail of FAG bearing boxes stacked at an angle"),
    ("0042", "stock-roulements-fag-rayonnage-perspective-tca", "showroom",
     "Perspective view of FAG bearing-box rack — strong red palette"),
    ("0096", "stock-courroies-renold-bea-cartons-tca", "showroom",
     "Stacked Renold/BEA red transmission/chain boxes labeled BEA 168"),
    ("0099", "stock-chaines-renold-sd-detail-tca", "showroom",
     "Detail of Renold SD industrial chain boxes side-on"),
    ("0259", "stock-rangement-bacs-bleus-quincaillerie-tca", "showroom",
     "Galvanized rack with rows of blue bins of small hardware"),

    # ---- SHOWROOM / STOCK GENERAL ----
    ("0022", "showroom-rayonnage-bacs-bleus-pneus-tca", "showroom",
     "Aisle view of red racking with blue bins and tires visible in the back"),
    ("0023", "showroom-allee-rayonnage-stock-tca", "showroom",
     "Showroom aisle with bins, pallet and tires in background"),
    ("0025", "showroom-bacs-bleus-detail-rayonnage-tca", "showroom",
     "Close-up of labeled blue parts bins on shelving"),
    ("0027", "showroom-bacs-bleus-perspective-tca", "showroom",
     "Perspective shot of small blue bins with diagonal rack lines"),
    ("0029", "showroom-bacs-bleus-detail-references-tca", "showroom",
     "Close-up of blue bins with size labels 52x68 etc"),
    ("0033", "showroom-bacs-bleus-rayonnage-detail-tca", "showroom",
     "Blue bins with parts in plastic bags on red rack"),
    ("0034", "showroom-bacs-bleus-pieces-detachees-tca", "showroom",
     "Detail of blue bins full of clear bagged spare parts"),
    ("0037", "showroom-rayonnage-pieces-detachees-bleu-rouge-tca", "showroom",
     "Two-tier rack of blue bins filled with bagged parts"),

    # ---- SPROCKETS / GEARS / TRANSMISSIONS (services + products) ----
    ("0058", "transmission-pignon-cartes-visite-tca", "services",
     "TCA business card stack standing in the hub of a chain sprocket"),
    ("0061", "transmission-pignon-blanc-carte-visite-tca", "services",
     "TCA business card framed by a white-painted sprocket"),
    ("0065", "transmission-pignons-rayonnage-stock-tca", "showroom",
     "Sprockets and pignons stored on a wooden shelf"),
    ("0069", "transmission-pignons-acier-detail-tca", "services",
     "Two stacks of steel sprockets in workshop light"),
    ("0074", "transmission-pignons-blancs-atelier-tca", "services",
     "Painted-white sprockets paired with raw steel on shelf"),
    ("0075", "transmission-pignon-dent-detail-tca", "services",
     "Macro of a large steel sprocket tooth in workshop"),
    ("0077", "transmission-pignon-grand-diametre-tca", "services",
     "Large-diameter sprocket and visible teeth on a wood plank"),
    ("0083", "transmission-pignons-acier-empiles-tca", "services",
     "Stacked sprockets seen edge-on with another in background"),
    ("0087", "transmission-rondelles-elastiques-bacs-tca", "products",
     "Rubber tendon couplings stored in blue plastic bins"),
    ("0093", "transmission-rondelles-elastiques-detail-tca", "products",
     "Close-up of rubber tendon coupling elements in blue bin"),
    ("0101", "transmission-pignons-axes-stock-tca", "services",
     "Multiple sprocket-axle assemblies stored on shelving"),
    ("0103", "transmission-pignons-axes-detail-tca", "services",
     "Close-up of paired sprockets mounted on axles, workshop ambience"),
    ("0105", "transmission-pignons-axes-empiles-tca", "services",
     "Stack of small sprocket-axle assemblies"),
    ("0107", "transmission-pignons-detail-dents-tca", "services",
     "Compact macro of a pignon's edge with teeth"),
    ("0110", "transmission-pignons-noirs-dent-detail-tca", "services",
     "Dark dramatic shot of three large interlocking sprockets"),
    ("0113", "transmission-pignons-rayonnage-empiles-tca", "services",
     "Multiple stacked sprockets seen from above on shelf"),
    ("0117", "transmission-grand-pignon-detail-tca", "services",
     "Detail of a very large dark gear with red rack support"),
    ("0120", "transmission-courroies-trapezoidales-stock-tca", "products",
     "Stack of looped trapezoidal V-belts on a metal pole"),
    ("0522", "transmission-poulies-acier-stock-tca", "products",
     "Row of V-belt pulleys arranged end-on, workshop bokeh background"),
    ("0528", "transmission-chaine-rouleaux-detail-tca", "products",
     "Macro of an industrial roller chain — links and rollers in detail"),

    # ---- CHAIN HOIST / PALAN ----
    ("0134", "atelier-palan-chaine-bleu-detail-tca", "atelier",
     "Blue chain-hoist gearbox top with descending chains"),
    ("0135", "atelier-palan-chaines-descendantes-detail-tca", "atelier",
     "Soft-focus chains hanging from a chain hoist"),
    ("0137", "atelier-palan-chaine-bleu-perspective-tca", "atelier",
     "Symmetrical view of chain hoist with chains falling diagonally"),
    ("0144", "atelier-potence-jaune-1600kg-detail-tca", "atelier",
     "Yellow workshop jib crane with 1600 kg lifting capacity"),
    ("0145", "atelier-palan-chaines-grises-detail-tca", "atelier",
     "Trio of gray hoist chains running over a sprocket"),

    # ---- WORKSHOP EQUIPMENT / OVERVIEW ----
    ("0152", "atelier-equipements-sablage-degraissage-tca", "atelier",
     "Workshop wall with sandblasting cabinet, parts-washing tank and dust extractor"),

    # ---- REDUCERS / REPAIRED COMPONENTS (atelier / services) ----
    ("0165", "atelier-reparation-reducteur-arbre-tca", "atelier",
     "Close-up of a worn shaft and bearing during reducer repair, yellow paint marks"),
    ("0166", "atelier-reparation-reducteur-engrenage-tca", "atelier",
     "Helical gear and bearing being assessed in workshop"),
    ("0167", "atelier-reparation-reducteur-pignon-detail-tca", "atelier",
     "Detail of helical gear meshing with tapered bearing during repair"),
    ("0169", "atelier-reparation-reducteur-arbre-pignon-tca", "atelier",
     "Splined pignon shaft mounted in a worn blue reducer housing"),
    ("0171", "atelier-reparation-carter-reducteur-tca", "atelier",
     "Dirty cast-iron housing fragment during reducer disassembly"),
    ("0172", "atelier-reparation-arbre-pignon-vert-tca", "atelier",
     "Splined pinion shaft pulled out of a teal-painted reducer"),
    ("0174", "atelier-roulement-cone-vert-tca", "atelier",
     "Tapered roller bearing being seated in a green-painted housing"),
    ("0179", "atelier-engrenage-helicoidal-arbre-tca", "atelier",
     "Helical gear on shaft resting on workshop wood plank"),
    ("0181", "atelier-engrenage-helicoidal-bois-tca", "atelier",
     "Helical gear on wooden plank in soft workshop light"),
    ("0182", "atelier-elingue-cable-acier-detail-tca", "atelier",
     "Coiled steel sling cable tied with green twine on yellow equipment"),
    ("0186", "atelier-reparation-poulie-jaune-detail-tca", "atelier",
     "Yellow worn part with cable harness during repair"),
    ("0196", "atelier-reducteur-conique-coupe-tca", "atelier",
     "Bevel/conical gear inside open reducer being inspected"),
    ("0198", "atelier-reducteur-conique-pignon-bleu-tca", "atelier",
     "Bevel pinion on shaft inside open blue gearbox housing"),
    ("0200", "atelier-engrenage-helicoidal-roulement-tca", "atelier",
     "Helical gear and tapered roller bearing on wooden block"),
    ("0202", "atelier-engrenage-helicoidal-noir-bois-tca", "atelier",
     "Dark helical gear in workshop, blue background blur"),
    ("0206", "atelier-moteur-vert-vintage-detail-tca", "atelier",
     "Worn green electric motor with rust patina, close-up"),
    ("0209", "atelier-reducteur-vert-roulement-tca", "atelier",
     "Sealed bearing inside a green reducer housing being inspected"),
    ("0210", "atelier-reducteur-vert-engrenage-interne-tca", "atelier",
     "Inside view through a window of a green reducer, helical gears visible"),
    ("0213", "atelier-reducteur-vert-engrenages-tca", "atelier",
     "Detailed view of helical gear chain inside a green gearbox"),
    ("0215", "atelier-reducteur-vert-carter-detail-tca", "atelier",
     "Detail of a green gearbox internal gear with carter cutaway"),
    ("0503", "atelier-reparation-reducteur-nord-vert-tca", "atelier",
     "Worn green Nord reducer with nameplate during repair"),
    ("0507", "atelier-reparation-reducteur-nord-detail-tca", "atelier",
     "Detail of a green Nord reducer housing during repair"),
    ("0408", "atelier-moteur-frein-acier-detail-tca", "atelier",
     "Detail of grey industrial motor with brake assembly"),
    ("0414", "atelier-reducteur-sew-marque-detail-tca", "atelier",
     "Close-up of SEW-branded reducer in workshop"),
    ("0470", "atelier-moteur-rotor-rouge-vue-axiale-tca", "atelier",
     "Axial view inside a blue/red painted motor showing rotor key"),
    ("0474", "atelier-reparation-tambour-bleu-jaune-tca", "atelier",
     "Worn blue industrial drum reducer with embossed star — under repair"),

    # ---- TECHNICIAN AT WORK (atelier — hands & gestures only) ----
    ("0226", "atelier-technicien-bornier-moteur-bleu-tca", "atelier",
     "Gloved technician hand intervening on the terminal box of a blue motor"),
    ("0227", "atelier-technicien-bornier-moteur-detail-tca", "atelier",
     "Technician hand pinching wire over electric motor terminal box"),
    ("0229", "atelier-technicien-gants-noirs-moteur-tca", "atelier",
     "Two gloved hands on a dusty motor base — black & white"),
    ("0230", "atelier-moteur-bornier-bleu-vue-aerienne-tca", "atelier",
     "Top-down B&W of an electric motor with terminal box open"),
    ("0232", "atelier-moteur-bornier-orange-detail-tca", "atelier",
     "Top view of a blue motor with orange terminal block visible"),
    ("0234", "atelier-moteur-bleu-bornier-ouvert-vue-tca", "atelier",
     "Wide top-down view of blue motor on workbench, terminal box open"),
    ("0250", "atelier-technicien-test-electrique-moteur-tca", "atelier",
     "Technician's gloved hands testing motor terminals with red and black probes"),
    ("0251", "atelier-moteur-bornier-test-isolement-tca", "atelier",
     "B&W detail of motor terminal block under test"),
    ("0257", "atelier-megohmetre-test-isolement-detail-tca", "atelier",
     "Megohmmeter and tester in their case showing reading on a workbench"),
    ("0260", "atelier-technicien-tournevis-rouge-bornier-tca", "atelier",
     "Hands using a red insulated screwdriver inside a motor terminal block"),
    ("0262", "atelier-technicien-test-megohmetre-moteur-bleu-tca", "atelier",
     "Hands using insulation tester probes on a large blue motor terminal block"),
    ("0285", "atelier-armoire-electrique-variateurs-detail-tca", "atelier",
     "Side view of an industrial cabinet with two variable-speed drive keypads"),
    ("0286", "atelier-armoire-electrique-construite-detail-tca", "atelier",
     "Custom-built electrical cabinet with sockets, push-buttons and HMI screen"),
    ("0288", "atelier-armoire-electrique-prises-detail-tca", "atelier",
     "Detailed close-up of blue sockets and marche/arret push-buttons on a cabinet"),
    ("0290", "atelier-armoire-electrique-prises-perspective-tca", "atelier",
     "Perspective view of an industrial cabinet — sockets and labelled push-buttons"),
    ("0291", "atelier-stock-pieces-detachees-bacs-tca", "showroom",
     "Tall rack of small blue bins for spare parts in stock area"),
    ("0295", "atelier-moteur-frein-gris-detail-tca", "atelier",
     "Industrial grey motor with brake disc visible, close-up"),
    ("0306", "atelier-technicien-cle-impact-dewalt-moteur-tca", "atelier",
     "Technician using a Dewalt cordless impact wrench on a motor coupling"),
    ("0307", "atelier-technicien-cle-impact-moteur-bornier-tca", "atelier",
     "Close-up of impact wrench in technician hand against a grey motor"),
    ("0310", "atelier-moteur-bornier-triphase-detail-tca", "atelier",
     "Three-phase motor terminal block with white/blue/red wires close-up"),
    ("0311", "atelier-technicien-extraction-flasque-moteur-tca", "atelier",
     "Hand removing the flange of a small motor on workbench"),
    ("0315", "atelier-technicien-extraction-flasque-detail-bw-tca", "atelier",
     "Gloved hand pulling the flange off a motor — black & white close-up"),
    ("0323", "atelier-technicien-flasque-rouleau-moteur-tca", "atelier",
     "Hand on motor flange, terminal block visible behind"),
    ("0339", "atelier-tournevis-mur-rangement-tca", "atelier",
     "Row of screwdrivers magnetically hung on OSB wall"),
    ("0340", "atelier-pignon-axe-detail-bokeh-tca", "atelier",
     "Small pinion mounted on a shaft, blurred workshop background"),
    ("0343", "atelier-bornier-moteur-orange-detail-tca", "atelier",
     "Close-up of an opened motor terminal box with orange insulators"),
    ("0363", "atelier-rotor-axe-pignon-detail-tca", "atelier",
     "Rotor shaft with double pignon stack rising out of a cylinder"),
    ("0366", "atelier-rotor-axe-pignon-flou-tca", "atelier",
     "Same rotor shaft and pignon stack, softer focus background"),
    ("0393", "atelier-detail-axe-acier-quadrille-tca", "atelier",
     "Macro of grooved metal cylinders next to brass parts"),
    ("0477", "atelier-technicien-fil-electrique-bw-tca", "atelier",
     "Technician's hands manipulating a wire over equipment — black & white"),
    ("0512", "showroom-stock-vis-boulons-bac-bleu-tca", "showroom",
     "Close-up of a blue bin of large metric bolts with reference label"),
    ("0515", "atelier-tournevis-king-tony-rangement-bw-tca", "atelier",
     "Row of King Tony screwdrivers hanging on OSB wall — black & white"),
    ("0523", "atelier-moteur-pompe-bleu-vintage-tca", "atelier",
     "Vintage blue pump motor with 'PUMP' label, rust patina, on pallet"),

    # ---- TEAM (flagged — needs Gabin's authorization) ----
    ("0367", "team-portrait-collaborateur-atelier-tca", "team",
     "FLAG: Black & white smiling portrait of a single TCA collaborator in the workshop. Per CLAUDE.md §3.3 and docs/client.md §8, individual team portraits require explicit authorization from TCA before any publication. Leave in folder for Gabin's decision."),

    # ---- 0268 — Technician with face visible (flag for review) ----
    ("0268", "atelier-technicien-portrait-reparation-moteur-bw-tca", "atelier",
     "FLAG: B&W portrait-style shot of a technician (face partially visible) working on a motor terminal. Same authorization concern as 0367 — flagged."),

    # ---- 0277 — Pressure gauge (atelier / services hydraulique-like) ----
    ("0277", "atelier-manometre-pression-detail-tca", "atelier",
     "Pressure gauge mounted on a black cylindrical canister — workshop detail"),
]


def convert_one(src: Path, dst: Path, max_kb: int) -> int:
    """Convert src JPG to dst WebP, retrying lower quality until under max_kb."""
    img = Image.open(src)
    for quality in (82, 78, 75, 70, 65, 60, 55, 50):
        img.save(dst, "webp", quality=quality, method=6)
        size_kb = dst.stat().st_size // 1024
        if size_kb <= max_kb:
            return size_kb
    return dst.stat().st_size // 1024  # accept best effort


def main() -> int:
    if not IMG_DIR.exists():
        print(f"ERROR: {IMG_DIR} not found", file=sys.stderr)
        return 1

    # Ensure subfolders
    for sub in ("hero", "atelier", "showroom", "services", "products", "team"):
        (IMG_DIR / sub).mkdir(exist_ok=True)

    print("orig,new,folder,size_kb,subject")
    seen_originals: set[str] = set()

    for orig_base, new_base, folder, subject in MAPPING:
        if orig_base in seen_originals:
            print(f"# SKIP duplicate mapping for {orig_base}", file=sys.stderr)
            continue
        seen_originals.add(orig_base)

        src = IMG_DIR / f"{orig_base}.jpg"
        if not src.exists():
            print(f"# MISSING source: {src}", file=sys.stderr)
            continue

        dst_dir = IMG_DIR / folder
        dst = dst_dir / f"{new_base}.webp"
        max_kb = 300 if folder == "hero" else 200

        try:
            size_kb = convert_one(src, dst, max_kb)
        except Exception as exc:
            print(f"# FAILED {orig_base}: {exc}", file=sys.stderr)
            continue

        # Confirm WebP exists and is non-empty
        if dst.exists() and dst.stat().st_size > 0:
            try:
                src.unlink()
            except Exception as exc:
                print(f"# could not delete source {src}: {exc}", file=sys.stderr)
        else:
            print(f"# WEBP missing after write: {dst}", file=sys.stderr)
            continue

        # Escape commas in subject for naive CSV
        safe_subject = subject.replace(",", ";")
        print(f"{orig_base}.jpg,{new_base}.webp,{folder},{size_kb},{safe_subject}")

    # Report any leftover JPGs (unmapped) for visibility
    leftover = sorted(p.name for p in IMG_DIR.glob("*.jpg"))
    if leftover:
        print(f"# LEFTOVER unmapped JPGs ({len(leftover)}): {', '.join(leftover)}",
              file=sys.stderr)

    return 0


if __name__ == "__main__":
    sys.exit(main())
