"""Fake REST API client interface for {{ interface_name }}.

Simulated REST client for testing without a live server.

Generated by: madsci new comm --template comm/rest
Template version: {{ template_version }}
"""

import logging
import time
from typing import Any, Optional

logger = logging.getLogger(__name__)


class {{ interface_name | pascal_case }}FakeInterface:
    """Fake REST client interface for testing {{ interface_name }} without a server.

    Simulates HTTP request/response behavior with configurable responses
    per endpoint and method.

    Example:
        >>> interface = {{ interface_name | pascal_case }}FakeInterface()
        >>> interface.set_response("GET", "/api/status", {"status": "ok"})
        >>> interface.connect()
        >>> result = interface.get("/api/status")
        >>> assert result == {"status": "ok"}
    """

    def __init__(
        self,
        base_url: str = "http://127.0.0.1:8080",
        timeout: float = 10.0,
        retry_count: int = 3,
        simulated_latency: float = 0.01,
        **kwargs: Any,
    ) -> None:
        """Initialize the fake REST client interface.

        Args:
            base_url: Simulated base URL.
            timeout: Simulated timeout.
            retry_count: Simulated retry count.
            simulated_latency: Artificial delay for each operation in seconds.
            **kwargs: Additional configuration (ignored).
        """
        self._base_url = base_url.rstrip("/")
        self._timeout = timeout
        self._retry_count = retry_count
        self._simulated_latency = simulated_latency
        self._is_connected = False
        self._responses: dict[str, dict] = {}
        self._request_history: list[dict[str, Any]] = []
        self._operation_count = 0

    @property
    def is_connected(self) -> bool:
        """Check if the session is active."""
        return self._is_connected

    @property
    def base_url(self) -> str:
        """Get the base URL."""
        return self._base_url

    @property
    def operation_count(self) -> int:
        """Get the total number of requests made."""
        return self._operation_count

    @property
    def request_history(self) -> list[dict[str, Any]]:
        """Get a copy of the request history."""
        return list(self._request_history)

    def set_response(self, method: str, endpoint: str, response: dict) -> None:
        """Configure a response for a given method and endpoint.

        Args:
            method: HTTP method (GET, POST, PUT, DELETE).
            endpoint: API endpoint path.
            response: Dictionary to return when this endpoint is requested.
        """
        key = f"{method.upper()}:{endpoint}"
        self._responses[key] = response

    def connect(self) -> None:
        """Simulate creating an HTTP session."""
        time.sleep(self._simulated_latency)
        self._is_connected = True
        logger.info(f"[FAKE] Connected to REST API at {self._base_url}")

    def disconnect(self) -> None:
        """Simulate closing the HTTP session."""
        if self._is_connected:
            self._is_connected = False
            logger.info(f"[FAKE] Disconnected from REST API at {self._base_url}")

    def _make_request(self, method: str, endpoint: str, data: Optional[dict] = None) -> dict:
        """Internal helper to simulate an HTTP request.

        Args:
            method: HTTP method.
            endpoint: API endpoint path.
            data: Optional request body.

        Returns:
            Configured response or empty dict.

        Raises:
            RuntimeError: If not connected.
        """
        if not self._is_connected:
            raise RuntimeError("Not connected. Call connect() first.")

        time.sleep(self._simulated_latency)
        self._operation_count += 1
        self._request_history.append({
            "method": method.upper(),
            "endpoint": endpoint,
            "data": data,
        })

        key = f"{method.upper()}:{endpoint}"
        return dict(self._responses.get(key, {}))

    def get(self, endpoint: str, **kwargs: Any) -> dict:
        """Simulate a GET request.

        Args:
            endpoint: API endpoint path.
            **kwargs: Additional parameters (ignored).

        Returns:
            Configured response dictionary.

        Raises:
            RuntimeError: If not connected.
        """
        return self._make_request("GET", endpoint)

    def post(self, endpoint: str, data: Optional[dict] = None, **kwargs: Any) -> dict:
        """Simulate a POST request.

        Args:
            endpoint: API endpoint path.
            data: JSON body to send.
            **kwargs: Additional parameters (ignored).

        Returns:
            Configured response dictionary.

        Raises:
            RuntimeError: If not connected.
        """
        return self._make_request("POST", endpoint, data)

    def put(self, endpoint: str, data: Optional[dict] = None, **kwargs: Any) -> dict:
        """Simulate a PUT request.

        Args:
            endpoint: API endpoint path.
            data: JSON body to send.
            **kwargs: Additional parameters (ignored).

        Returns:
            Configured response dictionary.

        Raises:
            RuntimeError: If not connected.
        """
        return self._make_request("PUT", endpoint, data)

    def delete(self, endpoint: str, **kwargs: Any) -> dict:
        """Simulate a DELETE request.

        Args:
            endpoint: API endpoint path.
            **kwargs: Additional parameters (ignored).

        Returns:
            Configured response dictionary.

        Raises:
            RuntimeError: If not connected.
        """
        return self._make_request("DELETE", endpoint)

    def reset(self) -> None:
        """Reset all internal state for test isolation."""
        self._responses = {}
        self._request_history = []
        self._operation_count = 0
