"""Metabotics v1 source SDK. Python 3.10+, standard library only.

This module is distributed with the repository; it is not a published PyPI package.
The API key authenticates to the application, not an enclosing private hosting gate.
"""

from __future__ import annotations

import ipaddress
import json
import math
from typing import Any, Mapping
from urllib.error import HTTPError, URLError
from urllib.parse import quote, urlsplit
from urllib.request import HTTPRedirectHandler, Request, build_opener


class MetaboticsError(Exception):
    """An application, transport, or hosting-gate error without credential values."""

    def __init__(self, status: int, code: str, message: str):
        self.status = status
        self.code = code
        self.message = message
        super().__init__(f"{code} ({status}): {message}")


class _NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        # Never forward the application key to a login page or a different origin.
        return None


def _segment(value: str) -> str:
    if not value or value in {".", ".."}:
        raise ValueError("A non-empty resource ID is required.")
    return quote(value, safe="")


class MetaboticsClient:
    """Client for a local, self-deployed, or separately authorized private Site.

    ``base_url`` is the origin (for example http://127.0.0.1:5173).
    ``access_headers`` can carry access information already supplied by your
    hosting provider. They do not bypass or create permission to access a Site.
    Browser/session-only operations such as API-key creation remain in Console.
    Writes are never retried automatically.
    """

    def __init__(
        self,
        base_url: str,
        api_key: str,
        *,
        timeout: float = 30,
        access_headers: Mapping[str, str] | None = None,
    ):
        parsed = urlsplit(base_url)
        host = parsed.hostname or ""
        try:
            loopback = ipaddress.ip_address(host).is_loopback
        except ValueError:
            loopback = host == "localhost"
        if parsed.scheme not in {"http", "https"} or not host:
            raise ValueError("base_url must be an absolute HTTP(S) origin.")
        if parsed.scheme == "http" and not loopback:
            raise ValueError("Use HTTPS outside loopback development.")
        if parsed.username or parsed.password or parsed.query or parsed.fragment or parsed.path not in {"", "/"}:
            raise ValueError("base_url must contain only an origin, with no credentials, path, query, or fragment.")
        if not api_key or not api_key.startswith(("mb_", "mbe_")):
            raise ValueError("Provide a workspace API key or a paired endpoint credential.")
        if not math.isfinite(timeout) or timeout <= 0:
            raise ValueError("timeout must be positive and finite.")
        self.base_url = base_url.rstrip("/")
        self.timeout = timeout
        self._api_key = api_key
        self._access_headers = dict(access_headers or {})
        for name in self._access_headers:
            lowered = name.lower()
            if lowered.startswith("oai-authenticated-") or lowered in {"x-metabotics-key", "host", "content-length", "content-type"}:
                raise ValueError(f"The access header {name!r} is reserved.")
        self._opener = build_opener(_NoRedirect())

    def _redact(self, value: str) -> str:
        for secret in [self._api_key, *self._access_headers.values()]:
            if secret:
                value = value.replace(secret, "[redacted]")
        return value

    def _request(self, method: str, path: str, body: dict[str, Any] | None = None) -> Any:
        headers = {
            **self._access_headers,
            "X-Metabotics-Key": self._api_key,
            "Accept": "application/json",
        }
        data = None
        if body is not None:
            data = json.dumps(body, ensure_ascii=False).encode("utf-8")
            headers["Content-Type"] = "application/json"
        request = Request(self.base_url + "/api/v1" + path, data=data, headers=headers, method=method)
        try:
            with self._opener.open(request, timeout=self.timeout) as response:
                payload = response.read()
                content_type = response.headers.get("Content-Type", "")
                if "json" not in content_type.lower():
                    raise MetaboticsError(response.status, "unexpected_response", "Expected JSON. Check the base URL and private hosting access.")
                return json.loads(payload)
        except HTTPError as error:
            status = error.code
            try:
                payload = json.loads(error.read())
                detail = payload.get("error", {}) if isinstance(payload, dict) else {}
                code = str(detail.get("code", "http_error"))
                message = str(detail.get("message", "The request was rejected."))
            except (ValueError, AttributeError):
                code = "hosting_access_required" if status in {301, 302, 303, 307, 308, 401, 403} else "http_error"
                message = "The server did not return API JSON. Check private hosting access and the API key."
            raise MetaboticsError(status, self._redact(code), self._redact(message)) from None
        except (TimeoutError, URLError):
            raise MetaboticsError(0, "transport_error", "The request could not complete. Check connectivity and timeout; inspect Console before retrying a write.") from None
        except (json.JSONDecodeError, UnicodeDecodeError):
            raise MetaboticsError(0, "invalid_json", "The server returned invalid JSON.") from None

    def get_state(self) -> dict[str, Any]:
        """Read the API key owner's workspace, including Souls and runtime mode."""
        return self._request("GET", "/bootstrap")

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

    def create_soul(self, name: str, *, personality: str | None = None, system_prompt: str | None = None) -> dict[str, Any]:
        body: dict[str, Any] = {"name": name}
        if personality is not None:
            body["personality"] = personality
        if system_prompt is not None:
            body["system_prompt"] = system_prompt
        return self._request("POST", "/souls", body)

    def update_soul(self, soul_id: str, **changes: Any) -> dict[str, Any]:
        return self._request("PATCH", f"/souls/{_segment(soul_id)}", changes)

    def delete_soul(self, soul_id: str) -> dict[str, Any]:
        return self._request("DELETE", f"/souls/{_segment(soul_id)}")

    def create_endpoint(self, soul_id: str, name: str, *, type: str = "api", capabilities: list[str] | None = None) -> dict[str, Any]:
        """Register a software/simulated endpoint; this does not attach hardware."""
        body: dict[str, Any] = {"soul_id": soul_id, "name": name, "type": type, "simulated": True}
        if capabilities is not None:
            body["capabilities"] = capabilities
        return self._request("POST", "/endpoints", body)

    def update_endpoint(self, endpoint_id: str, **changes: Any) -> dict[str, Any]:
        return self._request("PATCH", f"/endpoints/{_segment(endpoint_id)}", changes)

    def delete_endpoint(self, endpoint_id: str) -> dict[str, Any]:
        return self._request("DELETE", f"/endpoints/{_segment(endpoint_id)}")

    def add_memory(self, soul_id: str, content: str, *, scope: str = "shared", endpoint_id: str | None = None) -> dict[str, Any]:
        return self._request("POST", "/memories", {"soul_id": soul_id, "content": content, "scope": scope, "endpoint_id": endpoint_id})

    def delete_memory(self, memory_id: str) -> dict[str, Any]:
        return self._request("DELETE", f"/memories/{_segment(memory_id)}")

    def update_memory(self, memory_id: str, content: str) -> dict[str, Any]:
        return self._request("PATCH", f"/memories/{_segment(memory_id)}", {"content": content})

    def interact(self, soul_id: str, endpoint_id: str, message: str, *, action: dict[str, Any] | None = None) -> dict[str, Any]:
        body: dict[str, Any] = {"soul_id": soul_id, "endpoint_id": endpoint_id, "message": message}
        if action is not None:
            body["action"] = action
        return self._request("POST", "/interact", body)

    def evaluate(self) -> dict[str, Any]:
        """Run the reference-runtime consistency suite, not an LLM benchmark."""
        return self._request("POST", "/evaluate", {})

    def export_workspace(self) -> dict[str, Any]:
        return self._request("GET", "/export")

    def list_tools(self, *, request_id: int = 1) -> dict[str, Any]:
        return self._request("POST", "/mcp", {"jsonrpc": "2.0", "id": request_id, "method": "tools/list", "params": {}})

    def call_tool(self, name: str, arguments: dict[str, Any], *, request_id: int = 1) -> dict[str, Any]:
        return self._request("POST", "/mcp", {"jsonrpc": "2.0", "id": request_id, "method": "tools/call", "params": {"name": name, "arguments": arguments}})

    def connection_profiles(self) -> dict[str, Any]:
        return self._request("GET", "/connect/profiles")

    def connection_manifest(self, profile_id: str = "python-sdk") -> dict[str, Any]:
        return self._request("GET", f"/connect/manifest?profile={_segment(profile_id)}")

    def connection_preflight(self) -> dict[str, Any]:
        return self._request("GET", "/connect/preflight")

    def connection_status(self, session_id: str) -> dict[str, Any]:
        return self._request("GET", f"/connect/sessions/{_segment(session_id)}")

    def heartbeat(self) -> dict[str, Any]:
        """Requires a paired endpoint credential, not a workspace API key."""
        return self._request("POST", "/connect/heartbeat", {})
