import os
from pathlib import Path
import httpx

API_KEY = os.getenv("PEXELS_KEY", "Vc99rnmOhHhJAbgGQoKLZtsaIVfkeownoQNbTj78VemUjKh08ZYRbf18")
CACHE_DIR = Path("media/pexels")

def _client():
    return httpx.Client(
        base_url="https://api.pexels.com/v1/",
        headers={"Authorization": API_KEY},
        timeout=15,
    )

def fetch_first(query: str, orientation: str = "portrait") -> dict | None:
    if not API_KEY:
        return None
    try:
        with _client() as client:
            resp = client.get(
                "search",
                params={"query": query, "orientation": orientation, "per_page": 1, "page": 1},
            )
            resp.raise_for_status()
        data = resp.json()
        photo = (data.get("photos") or [None])[0]
        if not photo:
            return None
        src = photo["src"].get("large2x") or photo["src"].get("large") or photo["src"].get("original")
        CACHE_DIR.mkdir(parents=True, exist_ok=True)
        target = CACHE_DIR / f"{photo['id']}.jpg"
        if src:
            img = httpx.get(src, timeout=15)
            img.raise_for_status()
            target.write_bytes(img.content)
        return {
            "id": photo["id"],
            "local_path": f"pexels/{photo['id']}.jpg",
            "photographer": photo.get("photographer"),
            "photographer_url": photo.get("photographer_url"),
        }
    except Exception as e:
        print(f"Error fetching from Pexels: {e}")
        return None
