import httpx
import os
from dotenv import load_dotenv

load_dotenv(dotenv_path=os.path.join(os.path.dirname(__file__), "..", ".env"))

BASE_URL = os.getenv("APP_URL", "http://localhost:5000")
_keys    = os.getenv("API_KEYS", "")
API_KEY  = _keys.split(",")[0].strip() if _keys else ""


def post(endpoint: str, data: dict = None) -> dict | None:
    """POST to the local Flask API. Returns None on any error or 404."""
    try:
        resp = httpx.post(
            f"{BASE_URL}/{endpoint}",
            json=data or {},
            headers={"X-API-Key": API_KEY, "Accept": "application/json"},
            timeout=30.0,
        )
        if resp.status_code == 404:
            return None
        resp.raise_for_status()
        return resp.json()
    except Exception:
        return None
