#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ambil_url_das.py — Query Pexels untuk 10 artikel DAS premium, output daftar id+url ke JSON.
Tidak download gambar, hanya cari & pilih URL mobil Asia/premium (avoid sport/Lambo).
"""
import sys, os, json, time, requests

ROOT = os.path.dirname(os.path.abspath(__file__)) + "/.."
sys.path.insert(0, ROOT)
from pexels_image import PEXELS_KEYS, PEXELS_API

# query per artikel — prioritaskan MPV/SUV/van Asia & bengkel/mesin
QUERY_MAP = {
    "artikel-01": "car engine repair garage",
    "artikel-02": "car engine mechanic hands",
    "artikel-03": "car engine parts maintenance",
    "artikel-04": "luxury mpv van suv",
    "artikel-05": "car spare parts",
    "artikel-06": "auto repair shop car lift",
    "artikel-07": "car service center",
    "artikel-08": "car maintenance service",
    "artikel-09": "car engine closeup",
    "artikel-10": "suv car detail",
}
FALLBACKS = ["toyota alphard van", "mpv van car", "suv car asian", "car mechanic workshop"]

def flush(msg):
    print(msg, flush=True)

def find_photo(query):
    for key in PEXELS_KEYS:
        try:
            r = requests.get(PEXELS_API, params={"query": query, "per_page": 20, "orientation": "landscape"},
                             headers={"Authorization": key}, timeout=25)
            if r.status_code != 200:
                continue
            photos = r.json().get("photos", [])
            if photos:
                ph = photos[0]
                src = ph.get("src", {})
                return {
                    "id": ph.get("id"),
                    "url": src.get("large2x") or src.get("large") or src.get("original"),
                    "alt": ph.get("alt") or query,
                    "query": query,
                }
        except Exception as e:
            flush(f"  !! key error: {e}")
            time.sleep(1)
    return None

def main():
    out = {}
    for stem, q in QUERY_MAP.items():
        flush(f"=== {stem} | query: {q}")
        res = None
        for q2 in [q] + FALLBACKS:
            flush(f"  try: {q2}")
            res = find_photo(q2)
            if res:
                flush(f"  OK id={res['id']} alt={res['alt'][:50]}")
                out[stem] = res
                break
            time.sleep(1)
        if not res:
            flush(f"  !! GAGAL {stem}")
    with open("hasil_url_das.json", "w") as f:
        json.dump(out, f, indent=2)
    flush("\nDONE")

if __name__ == "__main__":
    main()
