import os
import requests
from pathlib import Path

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

def fetch_first(query: str, orientation: str = "landscape") -> dict | None:
    if not API_KEY:
        return None
    
    headers = {"Authorization": API_KEY}
    url = "https://api.pexels.com/v1/search"
    params = {"query": query, "orientation": orientation, "per_page": 1, "page": 1}
    
    try:
        resp = requests.get(url, 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": f"images/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
