"""HTTP client for PowerSun.vip REST API."""

from __future__ import annotations

from typing import Any

import httpx

BASE_URL = "https://powersun.vip"
TIMEOUT = 30.0


class PowerSunClient:
    """Lightweight HTTP client wrapping the PowerSun REST API."""

    def __init__(self, api_key: str | None = None, base_url: str = BASE_URL):
        self.base_url = base_url.rstrip("/")
        headers: dict[str, str] = {"User-Agent": "langchain-powersun/1.1.0"}
        if api_key:
            headers["X-API-Key"] = api_key
        self._client = httpx.Client(
            base_url=self.base_url,
            headers=headers,
            timeout=TIMEOUT,
        )

    def get(self, path: str) -> dict[str, Any]:
        r = self._client.get(path)
        r.raise_for_status()
        return r.json()

    def post(self, path: str, json: dict[str, Any] | None = None) -> dict[str, Any]:
        r = self._client.post(path, json=json or {})
        if r.status_code == 402:
            return {"error": "payment_required", **r.json()}
        r.raise_for_status()
        return r.json()

    def close(self) -> None:
        self._client.close()
