"""Mock API/Routes service."""

from typing import Any, Dict, Optional
from sed_sh.services.base import BaseService


class RoutesService(BaseService):
    """Service for managing mock API endpoints.

    All methods may raise SedSHError or its subclasses on error.
    """

    def create_endpoint(
        self,
        name: str,
        method: str,
        path: str,
        forward_mode: bool = False,
        forward_url: Optional[str] = None,
        response_status: Optional[int] = None,
        response_delay: Optional[int] = None,
        response_body: Optional[str] = None,
        response_headers: Optional[Dict[str, str]] = None,
        enabled: bool = True,
    ) -> Dict[str, Any]:
        """Create a mock API endpoint.

        Args:
            name: Endpoint name (for identification)
            method: HTTP method (GET, POST, PUT, DELETE, PATCH)
            path: API path (must start with /)
            forward_mode: If True, forward requests to forward_url
            forward_url: URL to forward requests to (required if forward_mode=True)
            response_status: HTTP status code to return (for mock mode)
            response_delay: Response delay in milliseconds (for mock mode)
            response_body: Response body string (for mock mode)
            response_headers: Response headers dict (for mock mode)
            enabled: Whether endpoint is enabled

        Returns:
            Dict containing:
                - endpointId (str): Unique endpoint identifier
                - name (str): Endpoint name
                - method (str): HTTP method
                - path (str): API path
                - url (str): Full endpoint URL
                - enabled (bool): Whether enabled
                - (additional fields depending on mode)

        Raises:
            InvalidRequestError: If parameters are invalid
            AuthenticationError: If API key is invalid
            SedSHError: On other errors

        Example:
            >>> # Mock mode
            >>> endpoint = client.routes.create_endpoint(
            ...     name="User API",
            ...     method="POST",
            ...     path="/api/users",
            ...     response_status=200,
            ...     response_body='{"success": true}',
            ...     response_headers={"Content-Type": "application/json"}
            ... )

            >>> # Forward mode
            >>> proxy = client.routes.create_endpoint(
            ...     name="Proxy API",
            ...     method="GET",
            ...     path="/api/data",
            ...     forward_mode=True,
            ...     forward_url="https://api.example.com/data"
            ... )
        """
        payload: Dict[str, Any] = {
            "name": name,
            "method": method,
            "path": path,
            "forwardMode": forward_mode,
            "enabled": enabled,
        }

        if forward_mode:
            if not forward_url:
                raise ValueError("forward_url is required when forward_mode=True")
            payload["forwardUrl"] = forward_url
        else:
            if response_status is not None:
                payload["responseStatus"] = response_status
            if response_delay is not None:
                payload["responseDelay"] = response_delay
            if response_body is not None:
                payload["responseBody"] = response_body
            if response_headers is not None:
                payload["responseHeaders"] = response_headers

        return self._request("POST", "/routes/endpoints", json=payload)

    def list_endpoints(self) -> Dict[str, Any]:
        """List all mock API endpoints.

        Returns:
            Dict containing:
                - endpoints (list): List of endpoint objects

        Raises:
            AuthenticationError: If API key is invalid
            SedSHError: On other errors

        Example:
            >>> endpoints = client.routes.list_endpoints()
            >>> for ep in endpoints['endpoints']:
            ...     print(f"{ep['method']} {ep['path']}")
        """
        return self._request("GET", "/routes/endpoints")

    def update_endpoint(
        self,
        endpoint_id: str,
        name: Optional[str] = None,
        method: Optional[str] = None,
        path: Optional[str] = None,
        forward_mode: Optional[bool] = None,
        forward_url: Optional[str] = None,
        response_status: Optional[int] = None,
        response_delay: Optional[int] = None,
        response_body: Optional[str] = None,
        response_headers: Optional[Dict[str, str]] = None,
        enabled: Optional[bool] = None,
    ) -> Dict[str, Any]:
        """Update an existing endpoint.

        Args:
            endpoint_id: Endpoint identifier
            (other args same as create_endpoint, all optional)

        Returns:
            Dict containing updated endpoint data

        Raises:
            ResourceNotFoundError: If endpoint doesn't exist
            InvalidRequestError: If parameters are invalid
            AuthenticationError: If API key is invalid
            SedSHError: On other errors

        Example:
            >>> updated = client.routes.update_endpoint(
            ...     endpoint_id="ep_123",
            ...     response_status=201
            ... )
        """
        payload: Dict[str, Any] = {}

        if name is not None:
            payload["name"] = name
        if method is not None:
            payload["method"] = method
        if path is not None:
            payload["path"] = path
        if forward_mode is not None:
            payload["forwardMode"] = forward_mode
        if forward_url is not None:
            payload["forwardUrl"] = forward_url
        if response_status is not None:
            payload["responseStatus"] = response_status
        if response_delay is not None:
            payload["responseDelay"] = response_delay
        if response_body is not None:
            payload["responseBody"] = response_body
        if response_headers is not None:
            payload["responseHeaders"] = response_headers
        if enabled is not None:
            payload["enabled"] = enabled

        return self._request("PUT", f"/routes/endpoints/{endpoint_id}", json=payload)

    def toggle_endpoint(self, endpoint_id: str, enabled: bool) -> Dict[str, Any]:
        """Toggle endpoint enabled/disabled status.

        Args:
            endpoint_id: Endpoint identifier
            enabled: True to enable, False to disable

        Returns:
            Dict containing success confirmation

        Raises:
            ResourceNotFoundError: If endpoint doesn't exist
            AuthenticationError: If API key is invalid
            SedSHError: On other errors

        Example:
            >>> client.routes.toggle_endpoint("ep_123", enabled=False)
        """
        return self._request(
            "PATCH", f"/routes/endpoints/{endpoint_id}/toggle", json={"enabled": enabled}
        )

    def delete_endpoint(self, endpoint_id: str) -> Dict[str, Any]:
        """Delete an endpoint.

        Args:
            endpoint_id: Endpoint identifier

        Returns:
            Dict containing success confirmation

        Raises:
            ResourceNotFoundError: If endpoint doesn't exist
            AuthenticationError: If API key is invalid
            SedSHError: On other errors

        Example:
            >>> client.routes.delete_endpoint("ep_123")
        """
        return self._request("DELETE", f"/routes/endpoints/{endpoint_id}")

    def get_requests(self) -> Dict[str, Any]:
        """Get list of requests received by all endpoints.

        Returns:
            Dict containing:
                - requests (list): List of request objects, each containing:
                    - requestId (str): Request identifier
                    - method (str): HTTP method
                    - path (str): Request path
                    - sourceIp (str): Client IP address
                    - timestamp (int): Unix timestamp
                    - (additional fields)

        Raises:
            AuthenticationError: If API key is invalid
            SedSHError: On other errors

        Example:
            >>> requests = client.routes.get_requests()
            >>> for req in requests['requests']:
            ...     print(f"{req['method']} {req['path']} from {req['sourceIp']}")
        """
        return self._request("GET", "/routes/requests")

    def get_request(self, request_id: str) -> Dict[str, Any]:
        """Get detailed information about a specific request.

        Args:
            request_id: Request identifier

        Returns:
            Dict containing full request details including headers, body, etc.

        Raises:
            ResourceNotFoundError: If request doesn't exist
            AuthenticationError: If API key is invalid
            SedSHError: On other errors

        Example:
            >>> req = client.routes.get_request("req_123")
            >>> print(f"Headers: {req['headers']}")
            >>> print(f"Body: {req['body']}")
        """
        return self._request("GET", f"/routes/requests/{request_id}")
