#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Cari beberapa foto model dari Pexels untuk contoh kreatif The Skin Code."""
import os
import sys

import requests
from PIL import Image

sys.path.insert(0, "/home/mantapman/.hermes/profiles/atun/workspace")
from pexels_image import PEXELS_KEYS  # noqa: E402

OUT = "/home/mantapman/.hermes/profiles/atun/workspace/tsc_ads_sample"
os.makedirs(OUT, exist_ok=True)

QUERIES = sys.argv[1:] or ["beauty portrait skincare", "woman glowing skin face"]
hasil = []
for q in QUERIES:
    for key in PEXELS_KEYS:
        try:
            r = requests.get("https://api.pexels.com/v1/search",
                             params={"query": q, "per_page": 8, "orientation": "portrait"},
                             headers={"Authorization": key}, timeout=30)
            if r.status_code != 200:
                print(f"  ⚠️ {q}: HTTP {r.status_code}")
                continue
            photos = r.json().get("photos", [])
            print(f"  {q}: {len(photos)} foto")
            for ph in photos:
                hasil.append({
                    "id": ph["id"],
                    "url": ph["src"].get("large2x") or ph["src"].get("large"),
                    "photographer": ph.get("photographer"),
                    "alt": (ph.get("alt") or "").strip()[:80],
                    "query": q,
                })
            break
        except Exception as e:
            print(f"  ⚠️ {q}: {e}")

# unduh 12 kandidat pertama
pilih = hasil[:12]
for i, ph in enumerate(pilih, 1):
    path = os.path.join(OUT, f"kandidat_{i:02d}.jpg")
    if not os.path.exists(path):
        try:
            img = requests.get(ph["url"], timeout=60,
                               headers={"User-Agent": "Mozilla/5.0"}).content
            with open(path, "wb") as f:
                f.write(img)
        except Exception as e:
            print(f"  gagal unduh {ph['id']}: {e}")
            continue
    ph["file"] = path
    with Image.open(path) as im:
        ph["ukuran"] = im.size
    print(f"{i:02d} | id={ph['id']} | {ph['ukuran']} | {ph['photographer']} | {ph['alt'][:60]}")

with open(os.path.join(OUT, "kandidat.json"), "w") as f:
    import json
    json.dump(pilih, f, indent=1)

# contact sheet 4x3 biar bisa dilihat sekaligus
lebar, tinggi = 360, 480
sisa = [p for p in pilih if p.get("file")]
if sisa:
    sheet = Image.new("RGB", (lebar * 4, tinggi * 3), (20, 20, 20))
    for i, ph in enumerate(sisa[:12]):
        with Image.open(ph["file"]) as im:
            im = im.convert("RGB")
            rasio = min(lebar / im.width, tinggi / im.height)
            im = im.resize((int(im.width * rasio), int(im.height * rasio)), Image.LANCZOS)
            x = (i % 4) * lebar + (lebar - im.width) // 2
            y = (i // 4) * tinggi + (tinggi - im.height) // 2
            sheet.paste(im, (x, y))
    sheet.save(os.path.join(OUT, "sheet_kandidat.jpg"), quality=88)
    print("sheet:", os.path.join(OUT, "sheet_kandidat.jpg"))
