"""HTTP client for Mango API."""

from typing import Any

import httpx


class MangoAPIError(Exception):
    """Error from Mango API."""

    def __init__(self, message: str, status_code: int | None = None):
        super().__init__(message)
        self.status_code = status_code


class MangoAPIClient:
    """Client for interacting with the Mango API."""

    def __init__(self, base_url: str, api_key: str):
        """Initialize the API client.

        Args:
            base_url: Base URL of the Mango API
            api_key: API key for authentication
        """
        self.base_url = base_url.rstrip("/")
        self.api_key = api_key
        self._client = httpx.Client(
            timeout=60.0,
            headers={
                "Authorization": f"Bearer {api_key}",
                "Content-Type": "application/json",
            },
        )

    def _request(
        self,
        method: str,
        path: str,
        json: dict[str, Any] | None = None,
    ) -> dict[str, Any]:
        """Make an API request.

        Args:
            method: HTTP method
            path: API path
            json: JSON body

        Returns:
            Response data

        Raises:
            MangoAPIError: If the request fails
        """
        url = f"{self.base_url}{path}"

        try:
            response = self._client.request(method, url, json=json)

            if response.status_code >= 400:
                try:
                    error_data = response.json()
                    message = error_data.get("detail", response.text)
                except Exception:
                    message = response.text
                raise MangoAPIError(message, response.status_code)

            return response.json()

        except httpx.RequestError as e:
            raise MangoAPIError(f"Request failed: {e}")

    def create_run(
        self,
        environment_name: str,
        model: str,
        rollouts: list[dict[str, Any]],
        config: dict[str, Any] | None = None,
    ) -> dict[str, Any]:
        """Create a new run with rollouts.

        Args:
            environment_name: Name of the environment
            model: Model name used for the run
            rollouts: List of rollout data
            config: Optional run configuration

        Returns:
            Created run data with id and dashboard_url
        """
        payload = {
            "environment_name": environment_name,
            "model": model,
            "rollouts": rollouts,
            "config": config or {},
        }

        return self._request("POST", "/v1/runs", json=payload)

    def get_environments(self) -> list[dict[str, Any]]:
        """Get list of environments.

        Returns:
            List of environment data
        """
        return self._request("GET", "/v1/environments")

    def get_environment(self, env_id: str) -> dict[str, Any]:
        """Get environment details.

        Args:
            env_id: Environment ID

        Returns:
            Environment data
        """
        return self._request("GET", f"/v1/environments/{env_id}")

    def get_run(self, run_id: str) -> dict[str, Any]:
        """Get run details.

        Args:
            run_id: Run ID

        Returns:
            Run data with rollouts
        """
        return self._request("GET", f"/v1/runs/{run_id}")

    def get_rollout(self, rollout_id: str) -> dict[str, Any]:
        """Get rollout details.

        Args:
            rollout_id: Rollout ID

        Returns:
            Rollout data with trace
        """
        return self._request("GET", f"/v1/rollouts/{rollout_id}")

    def close(self) -> None:
        """Close the HTTP client."""
        self._client.close()

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()
