"""API client for ReplyMarketing backend."""

from __future__ import annotations

from typing import Any, Optional

import httpx

from ..types import ApiResponse

API_BASE = "https://reply-marketing-api.vercel.app/api/v1"


class ApiClient:
    """HTTP client for ReplyMarketing API."""

    def __init__(self, api_key: Optional[str] = None) -> None:
        self.client = httpx.Client(
            base_url=API_BASE,
            timeout=30.0,
            headers={
                "Content-Type": "application/json",
                **({"Authorization": f"Bearer {api_key}"} if api_key else {}),
            },
        )

    def set_api_key(self, api_key: str) -> None:
        """Set API key for subsequent requests."""
        self.client.headers["Authorization"] = f"Bearer {api_key}"

    def _handle_response(self, response: httpx.Response) -> ApiResponse:
        """Handle HTTP response and return ApiResponse."""
        try:
            body = response.json() if response.content else {}
            
            if response.status_code >= 200 and response.status_code < 300:
                # Backend returns: { success: true, data: {...} }
                # Extract the actual data
                if isinstance(body, dict) and "data" in body:
                    return ApiResponse(success=True, data=body["data"])
                return ApiResponse(success=True, data=body)
            else:
                # Backend returns: { success: false, error: {...} }
                error_msg = body.get("error", {}).get("message", f"HTTP {response.status_code}")
                return ApiResponse(success=False, error=error_msg)
        except httpx.HTTPError as e:
            return ApiResponse(success=False, error=str(e))
        except Exception as e:
            return ApiResponse(success=False, error=f"Unexpected error: {e}")

    def get(self, path: str, **kwargs: Any) -> ApiResponse:
        """Make GET request."""
        try:
            response = self.client.get(path, **kwargs)
            return self._handle_response(response)
        except httpx.RequestError as e:
            return ApiResponse(success=False, error=f"Network error: {e}")

    def post(self, path: str, data: Optional[dict] = None, **kwargs: Any) -> ApiResponse:
        """Make POST request."""
        try:
            response = self.client.post(path, json=data, **kwargs)
            return self._handle_response(response)
        except httpx.RequestError as e:
            return ApiResponse(success=False, error=f"Network error: {e}")

    def put(self, path: str, data: Optional[dict] = None, **kwargs: Any) -> ApiResponse:
        """Make PUT request."""
        try:
            response = self.client.put(path, json=data, **kwargs)
            return self._handle_response(response)
        except httpx.RequestError as e:
            return ApiResponse(success=False, error=f"Network error: {e}")

    def delete(self, path: str, **kwargs: Any) -> ApiResponse:
        """Make DELETE request."""
        try:
            response = self.client.delete(path, **kwargs)
            return self._handle_response(response)
        except httpx.RequestError as e:
            return ApiResponse(success=False, error=f"Network error: {e}")

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

    def __enter__(self) -> ApiClient:
        return self

    def __exit__(self, *args: Any) -> None:
        self.close()
