#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
siapkan_featured_das.py — Download + crop 10 featured image DAS (WebP 1000x567).
Pakai 3 query yang TERBUKTI lolos 200: 'car', 'car mechanic garage', 'luxury car'.
Alokasi id UNIK tiap artikel (no duplikat).
Dipanggil per-arg-artikel supaya tidak hang di satu proses besar.
Usage: python3 siapkan_featured_das.py artikel-01
"""
import sys, os, json, time, io
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + "/..")
import requests
from pexels_image import PEXELS_KEYS, PEXELS_API
from PIL import Image

TARGET = os.path.dirname(os.path.abspath(__file__))
TRACKER = os.path.join(TARGET, ".das_featured_alloc.json")
QUERIES = ["car", "car mechanic garage", "luxury car"]

def load_alloc():
    if os.path.exists(TRACKER):
        try:
            return json.load(open(TRACKER))
        except Exception:
            return {"used": []}
    return {"used": []}

def save_alloc(data):
    with open(TRACKER, "w") as f:
        json.dump(data, f, indent=2)

def fetch_candidates(query):
    for key in PEXELS_KEYS:
        try:
            r = requests.get(PEXELS_API, params={"query": query, "per_page": 30, "orientation": "landscape"},
                             headers={"Authorization": key}, timeout=20)
            if r.status_code == 200:
                return r.json().get("photos", [])
        except Exception:
            time.sleep(1)
    return []

def pick_unused(used):
    # interleave antar query untuk variasi
    for q in QUERIES:
        for ph in fetch_candidates(q):
            pid = str(ph.get("id"))
            if pid in used:
                continue
            src = ph.get("src", {})
            url = src.get("large2x") or src.get("large") or src.get("original")
            if not url:
                continue
            used.append(pid)
            save_alloc({"used": used})
            return {"id": pid, "url": url, "alt": ph.get("alt") or q, "q": q}
    return None

def main(stem):
    used = load_alloc()["used"]
    res = pick_unused(used)
    if not res:
        print(f"GAGAL: tidak ada kandidat untuk {stem}", flush=True)
        return
    # download
    data = requests.get(res["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": res["id"], "q": res["q"], "alt": res["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} id={res['id']} q={res['q']} -> {out}", flush=True)

if __name__ == "__main__":
    main(sys.argv[1])
