from __future__ import annotations

import httpx
from typing import Any, Optional

_api_key: str = ""
_base_url: str = "http://localhost:3001"
_warned_missing_key: bool = False


def configure(api_key: str, base_url: Optional[str] = None) -> None:
    global _api_key, _base_url, _warned_missing_key
    _api_key = api_key
    _warned_missing_key = False
    if base_url:
        _base_url = base_url.rstrip("/")


def _ensure_api_key() -> bool:
    global _warned_missing_key
    if _api_key:
        return True
    if not _warned_missing_key:
        print("[ZappyBee] Missing API key. Call ZappyBee.init() (or TokenCat.init()) first.")
        _warned_missing_key = True
    return False


async def post(path: str, body: dict[str, Any]) -> Optional[dict[str, Any]]:
    if not _ensure_api_key():
        return None
    try:
        async with httpx.AsyncClient() as client:
            resp = await client.post(
                f"{_base_url}{path}",
                json=body,
                headers={"X-API-Key": _api_key, "Content-Type": "application/json"},
                timeout=30.0,
            )
            if resp.status_code >= 400:
                print(f"[ZappyBee] POST {path} failed: {resp.status_code}")
                return None
            return resp.json()
    except Exception as e:
        print(f"[ZappyBee] POST {path} error: {e}")
        return None


async def patch(path: str, body: dict[str, Any]) -> Optional[dict[str, Any]]:
    if not _ensure_api_key():
        return None
    try:
        async with httpx.AsyncClient() as client:
            resp = await client.patch(
                f"{_base_url}{path}",
                json=body,
                headers={"X-API-Key": _api_key, "Content-Type": "application/json"},
                timeout=30.0,
            )
            if resp.status_code >= 400:
                print(f"[ZappyBee] PATCH {path} failed: {resp.status_code}")
                return None
            return resp.json()
    except Exception as e:
        print(f"[ZappyBee] PATCH {path} error: {e}")
        return None
