from __future__ import annotations

from typing import Any, Dict, Optional

import requests


class PlytixApiClient:
    """Small configurable Plytix API client for source pulls."""

    def __init__(
        self,
        *,
        base_url: str,
        api_key: str = "",
        api_password: str = "",
        api_token: str = "",
        timeout_s: int = 60,
    ) -> None:
        self.base_url = str(base_url or "").strip().rstrip("/")
        if not self.base_url:
            raise ValueError("PLYTIX_API_BASE_URL is required")
        self.api_key = api_key
        self.api_password = api_password
        self.api_token = api_token
        self.timeout_s = timeout_s

    def get(self, path: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        url = self._url(path)
        response = requests.get(
            url,
            params=params or {},
            headers=self._headers(),
            auth=self._basic_auth(),
            timeout=self.timeout_s,
        )
        return self._parse_response(response)

    def post(self, path: str, json: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        url = self._url(path)
        response = requests.post(
            url,
            json=json or {},
            headers=self._headers(content_type=True),
            auth=self._basic_auth(),
            timeout=self.timeout_s,
        )
        return self._parse_response(response)

    def _url(self, path: str) -> str:
        return f"{self.base_url}/{str(path or '').strip().lstrip('/')}"

    def _basic_auth(self):
        if self.api_token:
            return None
        if self.api_key and self.api_password:
            return (self.api_key, self.api_password)
        return None

    def _parse_response(self, response: requests.Response) -> Dict[str, Any]:
        response.raise_for_status()
        payload = response.json()
        if isinstance(payload, list):
            return {"data": payload}
        if not isinstance(payload, dict):
            return {"data": []}
        return payload

    def _headers(self, *, content_type: bool = False) -> Dict[str, str]:
        headers = {"Accept": "application/json"}
        if content_type:
            headers["Content-Type"] = "application/json"
        if self.api_token:
            headers["Authorization"] = f"Bearer {self.api_token}"
            return headers
        if self.api_key:
            headers["apiKey"] = self.api_key
            headers["X-API-Key"] = self.api_key
        if self.api_password:
            headers["apiPassword"] = self.api_password
        return headers
