import os
from fastapi import Header, HTTPException
from dotenv import load_dotenv

def require_api_key(x_api_key: str | None = Header(default=None)):
    load_dotenv()
    expected = os.getenv("CABANNA_API_KEY", "").strip()

    if not expected:
        raise HTTPException(status_code=500, detail="Server missing CABANNA_API_KEY")

    if not x_api_key or x_api_key != expected:
        raise HTTPException(status_code=401, detail="Invalid API key")
