import os
from pathlib import Path
import requests

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

def fetch_first(query: str, orientation: str = "landscape") -> dict | None:
    if not API_KEY:
        return None
    try:
        headers = {"Authorization": API_KEY}
        params = {"query": query, "orientation": orientation, "per_page": 1, "page": 1}
        resp = requests.get("https://api.pexels.com/v1/search", headers=headers, params=params, timeout=15)
        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_resp = requests.get(src, timeout=15)
            img_resp.raise_for_status()
            target.write_bytes(img_resp.content)
            
        return {
            "id": photo["id"],
            "local_path": str(target),
            "photographer": photo.get("photographer"),
            "photographer_url": photo.get("photographer_url"),
            "url": f"/media/game_covers/{photo['id']}.jpg"
        }
    except Exception as e:
        print(f"Error fetching Pexels image: {e}")
        return None