#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
tahap_b_featured_das.py — Alokasikan + download + crop 10 featured image dari das_pool.json
ke WebP 1000x567. Pilih id NON-SPORT (sedan/SUV/luxury family) sesuai permintaan Bos
(dilarang sportscar/Lambo/racing).
"""
import sys, os, json, time, io
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + "/..")
import requests
from PIL import Image

TARGET = os.path.dirname(os.path.abspath(__file__))
POOL = json.load(open(os.path.join(TARGET, "das_pool.json")))

# id yang dipilih manual: SEDAN/SUV/luxury family (NON-SPORT)
ALOKASI = {
    "artikel-01": "261985",    # black luxury car studio -> overhaul
    "artikel-02": "34965678",  # blue luxury sedan urban -> biaya overhaul
    "artikel-03": "37094847",  # black sedan urban -> overhaul dini vs darurat
    "artikel-04": "17792392",  # black Maybach -> bengkel premium
    "artikel-05": "3764984",   # white luxury car urban -> suku cadang
    "artikel-06": "13236247",  # luxury black car urban -> bengkel terbaik
    "artikel-07": "29813834",  # high-end silver car -> resmi vs spesialis
    "artikel-08": "12770250",  # white SUV from above -> ritual perawatan
    "artikel-09": "27659273",  # elegant black sedan -> mitos fakta
    "artikel-10": "23507111",  # Dodge Charger sedan -> perawatan premium
}

def find(id_):
    for c in POOL:
        if c["id"] == id_:
            return c
    return None

def main():
    for stem, pid in ALOKASI.items():
        c = find(pid)
        if not c:
            print(f"MISS {stem} id {pid}", flush=True); continue
        try:
            data = requests.get(c["url"], timeout=40).content
            im = Image.open(io.BytesIO(data)).convert("RGB")
            w, h = im.size
            tw, th = 1000, 567
            target = tw / th
            curr = w / h
            if curr > target:
                nw = int(h * target); left = (w - nw) // 2
                im = im.crop((left, 0, left + nw, h))
            else:
                nh = int(w / target); top = (h - nh) // 2
                im = im.crop((0, top, w, top + nh))
            im = im.resize((tw, th), Image.LANCZOS)
            out = os.path.join(TARGET, f"{stem}-featured.webp")
            im.save(out, "WEBP", quality=90)
            meta = {"id": pid, "q": c["q"], "alt": c["alt"], "out": out}
            with open(os.path.join(TARGET, f"{stem}-featured.json"), "w") as f:
                json.dump(meta, f, indent=2)
            print(f"OK {stem} -> {out} ({c['alt'][:40]})", flush=True)
        except Exception as e:
            print(f"ERR {stem}: {e}", flush=True)

if __name__ == "__main__":
    main()
