"""
SHIP Protocol HTTP Client

Simple HTTP client for communicating with the SHIP API.
Uses httpx for consistent async/sync support.

Design Principles:
    - Antifragile: Timeout and error handling on every request
    - Observable: Structured responses with error context
    - Minimal: No unnecessary abstractions
"""

from typing import Any, Dict, Optional

import httpx


DEFAULT_BASE_URL = "https://ship-protocol.dhruvaapi.workers.dev"
DEFAULT_TIMEOUT = 30.0


class SHIPClient:
    """
    HTTP client for the SHIP Protocol API.

    Handles all HTTP communication with the SHIP scoring and detection endpoints.
    Uses httpx for reliable HTTP with timeout support.

    Usage:
        ```python
        client = SHIPClient()
        result = client.score("owner/repo")
        ```
    """

    def __init__(
        self,
        base_url: str = DEFAULT_BASE_URL,
        api_key: Optional[str] = None,
        timeout: float = DEFAULT_TIMEOUT,
    ) -> None:
        """
        Initialize SHIP API client.

        Args:
            base_url: SHIP API base URL
            api_key: Optional API key for authenticated requests
            timeout: Request timeout in seconds
        """
        self.base_url = base_url.rstrip("/")
        self.api_key = api_key
        self.timeout = timeout

    def _get_headers(self) -> Dict[str, str]:
        """Build request headers."""
        headers: Dict[str, str] = {
            "Content-Type": "application/json",
            "User-Agent": "ship-crewai/1.0.0",
        }
        if self.api_key:
            headers["Authorization"] = f"Bearer {self.api_key}"
        return headers

    def _build_client(self) -> httpx.Client:
        """Create a configured httpx client."""
        return httpx.Client(
            base_url=self.base_url,
            headers=self._get_headers(),
            timeout=self.timeout,
        )

    def score(self, repo: str) -> Dict[str, Any]:
        """
        Score a GitHub repository for AI code reliability.

        Args:
            repo: GitHub repository in "owner/repo" format

        Returns:
            Dict with score, grade, breakdown, and metadata

        Raises:
            httpx.HTTPStatusError: On non-2xx responses
            httpx.TimeoutException: On timeout
        """
        with self._build_client() as client:
            response = client.post(
                "/v2/score",
                json={"repo": repo},
            )
            response.raise_for_status()
            return response.json()

    def detect(self, code: str, language: str = "python") -> Dict[str, Any]:
        """
        Detect whether code is AI-generated.

        Args:
            code: Source code to analyze
            language: Programming language of the code

        Returns:
            Dict with ai_probability, is_ai_generated flag, and feature analysis

        Raises:
            httpx.HTTPStatusError: On non-2xx responses
            httpx.TimeoutException: On timeout
        """
        with self._build_client() as client:
            response = client.post(
                "/v2/detect",
                json={"code": code, "language": language},
            )
            response.raise_for_status()
            return response.json()

    def health(self) -> Dict[str, Any]:
        """
        Check SHIP API health status.

        Returns:
            Dict with status, version, and uptime info

        Raises:
            httpx.HTTPStatusError: On non-2xx responses
            httpx.TimeoutException: On timeout
        """
        with self._build_client() as client:
            response = client.get("/health")
            response.raise_for_status()
            return response.json()
