#!/usr/bin/env python3
"""Segunda passada: focar em cama, sofa, cadeira em casa - com maos atras da cabeca ou ocio explicito."""
import requests, json, os

PEXELS_KEY = "YDqxXGXvOaPQnitSVyxbhghbH49w95DV2fbAkynBjNVvus1TI60Qffdo"

QUERIES = [
    "man laying couch relaxed eyes closed",
    "man napping sofa hands behind head",
    "man resting on bed hands behind head",
    "man daydreaming couch",
    "man peaceful sleeping couch",
    "man lying back sofa peaceful",
    "man sofa hands behind head home",
    "man taking break sofa home",
    "man reclining home living room",
    "person laying couch peaceful",
    "man relaxing sunday morning",
    "guy lounging home sofa",
    "man napping home",
]

out_dir = "/opt/mia/workspace/clientes/px3lab/lancamento_photorf2/criativos/pexels_relax_v2"
os.makedirs(out_dir, exist_ok=True)

results = []
seen_ids = set()

for q in QUERIES:
    r = requests.get(
        "https://api.pexels.com/v1/search",
        headers={"Authorization": PEXELS_KEY},
        params={"query": q, "per_page": 15, "orientation": "landscape"},
    )
    if r.status_code != 200:
        print(f"[!] {q}: {r.status_code}")
        continue
    data = r.json()
    for p in data.get("photos", []):
        pid = p["id"]
        if pid in seen_ids:
            continue
        seen_ids.add(pid)
        results.append({
            "id": pid, "query": q, "alt": p.get("alt", ""),
            "url": p["url"], "src_large2x": p["src"]["large2x"],
            "width": p["width"], "height": p["height"],
        })

print(f"Total: {len(results)} fotos unicas")

with open(f"{out_dir}/results.json", "w") as f:
    json.dump(results, f, indent=2, ensure_ascii=False)

# Filtra semanticamente antes de baixar
priority = ["hands behind head", "arms behind head", "reclining", "lying back", "laying back",
            "laying on couch", "laying on sofa", "napping", "eyes closed", "peaceful", "daydream",
            "lounging", "relaxing on"]
exclude = ["shirtless", "gym", "workout", "yoga", "stretching", "beach", "exercise",
           "silhouette", "outdoor", "window looking", "office"]

top = []
for i, p in enumerate(results):
    alt = p.get("alt", "").lower()
    if any(x in alt for x in exclude):
        continue
    score = sum(2 for t in priority if t in alt)
    if score > 0:
        top.append((score, i, p))

top.sort(key=lambda x: -x[0])
print(f"\nTOP {len(top)} filtradas:")
for s, i, p in top[:30]:
    print(f"  score={s}  idx={i:03d}  id={p['id']}  {p['alt'][:100]}")

# Baixa top 30
for s, i, p in top[:30]:
    fname = f"{out_dir}/{i:03d}_{p['id']}.jpg"
    if os.path.exists(fname):
        continue
    try:
        img = requests.get(p["src_large2x"], timeout=30)
        with open(fname, "wb") as f:
            f.write(img.content)
    except Exception as e:
        print(f"  [!] {p['id']}: {e}")

print("Done.")
