from __future__ import annotations

import os
from typing import Any

from ._constants import DEFAULT_BASE_URL, DEFAULT_TIMEOUT
from ._exceptions import (
    APIError,
    AuthenticationError,
    InternalServerError,
    NotFoundError,
    PermissionDeniedError,
    RungateError,
)
from ._response import RungateResponse
from ._version import __version__


class AdminBaseClient:
    """Shared HTTP logic for Admin clients. Uses admin token auth.

    Key differences from agent BaseClient:
    - Auth: admin token (rg_adm_*) or dashboard password, NOT agent API key
    - Error format: admin 401 returns {"error": "string"} not {"error": {...}}
    - No connection retries (management operations, not latency-sensitive)
    - All paths prefixed with /api/ (admin API, not proxy /v1/)
    - No governance error handling (admin endpoints don't return governance blocks)
    """

    def __init__(
        self,
        token: str | None = None,
        base_url: str | None = None,
        timeout: float = DEFAULT_TIMEOUT,
    ) -> None:
        self.token = token or os.environ.get("RUNGATE_ADMIN_TOKEN") or os.environ.get("RUNGATE_DASHBOARD_PASSWORD")
        if not self.token:
            raise RungateError("Admin token is required. Pass token= or set RUNGATE_ADMIN_TOKEN environment variable.")
        self.base_url = (base_url or os.environ.get("RUNGATE_BASE_URL") or DEFAULT_BASE_URL).rstrip("/")
        self.timeout = timeout

    def _build_headers(self) -> dict[str, str]:
        return {
            "Authorization": f"Bearer {self.token}",
            "Content-Type": "application/json",
            "User-Agent": f"rungate-python/{__version__}",
        }

    def _build_url(self, path: str) -> str:
        return f"{self.base_url}{path}"

    def _handle_response(self, response: RungateResponse) -> RungateResponse:
        """Admin-specific error handling."""
        status = response.status_code
        if 200 <= status < 300:
            return response

        body = response.body
        error_data = body.get("error", {}) if isinstance(body, dict) else {}

        # Handle flat string error (admin 401 format: {"error": "Authentication required"})
        if isinstance(error_data, str):
            message = error_data
        elif isinstance(error_data, dict):
            message = error_data.get("message", f"HTTP {status}")
        else:
            message = f"HTTP {status}"

        error_kwargs: dict[str, Any] = {"message": message, "status_code": status, "body": body}

        if status == 401:
            raise AuthenticationError(**error_kwargs)
        elif status == 403:
            raise PermissionDeniedError(**error_kwargs)
        elif status == 404:
            raise NotFoundError(**error_kwargs)
        elif status >= 500:
            raise InternalServerError(**error_kwargs)
        else:
            raise APIError(**error_kwargs)
