from __future__ import annotations

import httpx
from typing import Any, Dict, Optional

from ..exceptions import ApiError
from ..config import AribaConfig


class AribaClient:
    """
    Minimal HTTP client skeleton for Ariba-style APIs.
    You can adapt endpoints per your tenant (Ariba APIs vary by configuration).
    """

    def __init__(self, config: AribaConfig, timeout_s: float = 30.0):
        self.config = config
        self.timeout_s = timeout_s

    def _headers(self) -> Dict[str, str]:
        return {
            "Authorization": f"Bearer {self.config.token}",
            "Accept": "application/json",
            "Content-Type": "application/json",
        }

    async def get(self, path: str, params: Optional[Dict[str, Any]] = None) -> Any:
        url = self.config.base_url.rstrip("/") + "/" + path.lstrip("/")
        async with httpx.AsyncClient(timeout=self.timeout_s) as client:
            r = await client.get(url, headers=self._headers(), params=params)
        if r.status_code >= 400:
            raise ApiError(f"GET {url} failed: {r.status_code} {r.text[:500]}")
        return r.json()

    async def post(self, path: str, payload: Dict[str, Any]) -> Any:
        url = self.config.base_url.rstrip("/") + "/" + path.lstrip("/")
        async with httpx.AsyncClient(timeout=self.timeout_s) as client:
            r = await client.post(url, headers=self._headers(), json=payload)
        if r.status_code >= 400:
            raise ApiError(f"POST {url} failed: {r.status_code} {r.text[:500]}")
        return r.json()

