"""{{ interface_description }}

REST API client interface for HTTP-based instrument communication.

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

import logging
from typing import Any, Optional

logger = logging.getLogger(__name__)


class {{ interface_name | pascal_case }}Interface:
    """REST API client interface for {{ interface_name }}.

    Provides HTTP-based communication with connect/disconnect and standard
    HTTP method operations (GET, POST, PUT, DELETE).

    Example:
        >>> interface = {{ interface_name | pascal_case }}Interface(base_url="http://192.168.1.100:8080")
        >>> interface.connect()
        >>> status = interface.get("/api/status")
        >>> interface.post("/api/command", data={"action": "run"})
        >>> interface.disconnect()
    """

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

        Args:
            base_url: Base URL of the REST API (e.g., http://host:port).
            timeout: Request timeout in seconds.
            retry_count: Number of retry attempts for failed requests.
            **kwargs: Additional HTTP client options.
        """
        self._base_url = base_url.rstrip("/")
        self._timeout = timeout
        self._retry_count = retry_count
        self._config = kwargs
        self._session: Any = None
        self._is_connected = False

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

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

    def connect(self) -> None:
        """Create an HTTP session and verify connectivity.

        Raises:
            ConnectionError: If the server is unreachable.
        """
        logger.info(f"Connecting to REST API at {self._base_url}...")

        # TODO: Implement actual HTTP session creation
        # import httpx
        # self._session = httpx.Client(
        #     base_url=self._base_url,
        #     timeout=self._timeout,
        #     **self._config,
        # )
        # # Optionally verify connectivity
        # self._session.get("/health")

        self._is_connected = True
        logger.info(f"Connected to REST API at {self._base_url}")

    def disconnect(self) -> None:
        """Close the HTTP session."""
        if self._is_connected:
            logger.info(f"Disconnecting from REST API at {self._base_url}...")

            # TODO: Close actual session
            # if self._session:
            #     self._session.close()

            self._is_connected = False
            self._session = None
            logger.info(f"Disconnected from REST API at {self._base_url}")

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

        Args:
            endpoint: API endpoint path (e.g., "/api/status").
            **kwargs: Additional request parameters (params, headers, etc.).

        Returns:
            Parsed JSON response as a dictionary.

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

        url = f"{self._base_url}{endpoint}"
        logger.debug(f"GET {url}")

        # TODO: Implement actual GET request
        # response = self._session.get(endpoint, **kwargs)
        # response.raise_for_status()
        # return response.json()

        return {}

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

        Args:
            endpoint: API endpoint path.
            data: JSON body to send.
            **kwargs: Additional request parameters.

        Returns:
            Parsed JSON response as a dictionary.

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

        url = f"{self._base_url}{endpoint}"
        logger.debug(f"POST {url}")

        # TODO: Implement actual POST request
        # response = self._session.post(endpoint, json=data, **kwargs)
        # response.raise_for_status()
        # return response.json()

        return {}

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

        Args:
            endpoint: API endpoint path.
            data: JSON body to send.
            **kwargs: Additional request parameters.

        Returns:
            Parsed JSON response as a dictionary.

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

        url = f"{self._base_url}{endpoint}"
        logger.debug(f"PUT {url}")

        # TODO: Implement actual PUT request
        # response = self._session.put(endpoint, json=data, **kwargs)
        # response.raise_for_status()
        # return response.json()

        return {}

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

        Args:
            endpoint: API endpoint path.
            **kwargs: Additional request parameters.

        Returns:
            Parsed JSON response as a dictionary.

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

        url = f"{self._base_url}{endpoint}"
        logger.debug(f"DELETE {url}")

        # TODO: Implement actual DELETE request
        # response = self._session.delete(endpoint, **kwargs)
        # response.raise_for_status()
        # return response.json()

        return {}
