#!/usr/bin/env python3
"""
yasma_pexels_retry.py
Automatic retry to fetch 4 missing Yasma featured images from Pexels.
Runs via cron until all 4 are fetched (then self-disables nothing; cron continues but script exits early when files exist).
Safe: only touches yasma_seo_5/featured_*.webp
"""
import requests, io, os, time, sys
from PIL import Image

BASE = "/home/mantapman/.hermes/profiles/atun/workspace/yasma_seo_5"
KEYS = [
    "563492ad6f917000010000017b9a8b65e2d64d0b8f420f29b33cbbac",
    "5740bd5eb63aa34190a467353fce66a3",
    "9217ef5fcb758f64bb135c13ea55ff5c",
    "e769aa130647d2354c40ea6a439bfc08",
]
JOBS = [
    ("a1_maklon", "beverage factory"),
    ("a2_kolagen", "cosmetic laboratory"),
    ("a3_adaptogen", "herbal plant"),
    ("a5_suplemen", "healthy drink"),
]
DONE_MARKER = os.path.join(BASE, "yasma_pexels_done.flag")

def fetch_featured(q):
    for key in KEYS:
        try:
            r = requests.get("https://api.pexels.com/v1/search",
                             params={"query": q, "per_page": 12, "orientation": "landscape"},
                             headers={"Authorization": key}, timeout=30)
            if r.status_code == 200:
                for ph in r.json().get("photos", []):
                    src = ph["src"]
                    u = src.get("large2x") or src.get("large") or src.get("original")
                    if u:
                        return ph, u
        except Exception:
            pass
        time.sleep(2)
    return None, None

def main():
    if os.path.exists(DONE_MARKER):
        print("done marker exists; skip")
        return 0

    missing = [j for j in JOBS if not os.path.exists(os.path.join(BASE, f"featured_{j[0]}.webp"))]
    if not missing:
        open(DONE_MARKER, "w").write(time.strftime("%Y-%m-%d %H:%M:%S") + "\n")
        print("all images present; done")
        return 0

    saved = 0
    for name, q in missing:
        out_p = os.path.join(BASE, f"featured_{name}.webp")
        if os.path.exists(out_p):
            continue
        ph, u = fetch_featured(q)
        if not ph:
            print(f"{name}: no valid pexels result")
            continue
        dr = requests.get(u, timeout=50, headers={"User-Agent": "Mozilla/5.0"})
        if dr.status_code != 200:
            print(f"{name}: download {dr.status_code}")
            continue
        im = Image.open(io.BytesIO(dr.content)).convert("RGB")
        w, h = im.size
        tg = 1000 / 567
        cur = w / h
        if cur > tg:
            nw = int(h * tg); l = (w - nw) // 2
            im = im.crop((l, 0, l + nw, h))
        else:
            nh = int(w / tg); t = (h - nh) // 2
            im = im.crop((0, t, w, t + nh))
        im = im.resize((1000, 567), Image.LANCZOS)
        im.save(out_p, "WEBP", quality=90)
        print(f"{name}: OK pexels {ph['id']} ({os.path.getsize(out_p)//1024}KB)")
        saved += 1
        time.sleep(3)

    if saved and not [j for j in JOBS if not os.path.exists(os.path.join(BASE, f"featured_{j[0]}.webp"))]:
        open(DONE_MARKER, "w").write(time.strftime("%Y-%m-%d %H:%M:%S") + "\n")
        print("all fetched; done")
    return 0

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