"""Gateway HTTP client."""

from __future__ import annotations

import json
import urllib.error
import urllib.request
from dataclasses import dataclass
from typing import Any

from memnixa.gateway.messages import InboundMessageContext


@dataclass(slots=True)
class GatewayClient:
    """Minimal HTTP client for the Memnixa gateway."""

    base_url: str
    timeout: int = 120

    def health(self) -> dict[str, Any]:
        """Check gateway health."""
        return self._request("GET", "/health")

    def run_agent(self, inbound: InboundMessageContext) -> dict[str, Any]:
        """Send one agent request through the gateway."""
        payload = {
            "session_id": inbound.session_id,
            "run_id": inbound.run_id,
            "message_id": inbound.message_id,
            "raw_body": inbound.raw_body,
            "body_for_agent": inbound.body_for_agent,
            "received_at": inbound.received_at,
            "source_mode": inbound.source_mode,
            "channel": inbound.channel,
            "launch_cwd": inbound.launch_cwd,
            "entrypoint_path": inbound.entrypoint_path,
            "python_executable": inbound.python_executable,
            "actor_identity_status": inbound.actor_identity_status,
            "actor_user_id": inbound.actor_user_id,
            "actor_role": inbound.actor_role,
            "actor_external_id": inbound.actor_external_id,
            "actor_is_owner": inbound.actor_is_owner,
        }
        return self._request("POST", "/v1/agent/run", payload)

    def export_memory(self) -> dict[str, Any]:
        """Export all long-term memory items from the gateway."""
        return self._request("GET", "/v1/memory/export")

    def _request(
        self,
        method: str,
        path: str,
        payload: dict[str, Any] | None = None,
    ) -> dict[str, Any]:
        body = None
        headers = {"User-Agent": "MemnixaGatewayClient/0.1.0"}
        if payload is not None:
            body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
            headers["Content-Type"] = "application/json"
        request = urllib.request.Request(
            url=f"{self.base_url.rstrip('/')}{path}",
            data=body,
            headers=headers,
            method=method,
        )
        try:
            with urllib.request.urlopen(request, timeout=self.timeout) as response:
                return json.loads(response.read().decode("utf-8"))
        except urllib.error.HTTPError as exc:
            detail = exc.read().decode("utf-8", errors="replace")
            raise RuntimeError(f"gateway HTTP {exc.code}: {detail}") from exc
        except urllib.error.URLError as exc:
            raise RuntimeError(f"gateway network error: {exc}") from exc
