"""Signet daemon HTTP client.

Communicates with the Signet daemon on 127.0.0.1:3850 (default) for
memory operations: search, store, hooks, and session lifecycle.

Configuration resolution:
  1. SIGNET_HOST + SIGNET_PORT env vars
  2. SIGNET_DAEMON_URL env var (full URL override)
  3. Default: http://127.0.0.1:3850
"""

from __future__ import annotations

import json
import logging
import math
import os
import ipaddress
import http.client
import urllib.error
import urllib.parse
import urllib.request
from typing import Any, Dict, List, Optional

logger = logging.getLogger(__name__)

_DEFAULT_HOST = "127.0.0.1"
_DEFAULT_PORT = 3850
_TIMEOUT_SECS = 5
_LONG_TIMEOUT_SECS = 15
_RECALL_TIMEOUT_SECS = 30
_TRUSTED_ORIGINS_ENV = "SIGNET_TRUSTED_DAEMON_ORIGINS"


def _sanitize(value: str) -> str:
    """Strip leading/trailing whitespace and embedded newlines from env values."""
    return value.strip().replace("\r", "").replace("\n", "")


def _normalize_recall_limit(value: Any) -> int:
    """Match the versioned Signet recall request contract."""
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        return 10
    if isinstance(value, float) and not math.isfinite(value):
        return 10
    return min(100, max(1, math.trunc(value)))


def _build_recall_request_body(
    query: str,
    *,
    limit: Any = None,
    project: str = "",
    memory_type: str = "",
    tags: str = "",
    who: str = "",
    pinned: Optional[bool] = None,
    importance_min: Optional[float] = None,
    since: str = "",
    until: str = "",
    keyword_query: str = "",
    aggregate: bool = False,
    aggregate_budget: str = "",
    save_aggregate: Optional[bool] = None,
    min_score: Optional[float] = None,
    agent_id: str = "",
    recall_surface: str = "",
) -> Dict[str, Any]:
    """Build canonical daemon JSON for the options exposed by Hermes."""
    body: Dict[str, Any] = {"query": query, "limit": _normalize_recall_limit(limit)}
    optional_strings = {
        "project": project,
        "type": memory_type,
        "tags": tags,
        "who": who,
        "since": since,
        "until": until,
        "keywordQuery": keyword_query,
        "agentId": agent_id,
    }
    body.update({key: value for key, value in optional_strings.items() if value})
    if pinned is True:
        body["pinned"] = True
    if importance_min is not None:
        body["importance_min"] = importance_min
    if aggregate is True:
        body["aggregate"] = True
    if aggregate_budget in ("small", "medium", "large"):
        body["aggregateBudget"] = aggregate_budget
    if isinstance(save_aggregate, bool):
        body["saveAggregate"] = save_aggregate
    if isinstance(min_score, (int, float)) and not isinstance(min_score, bool) and math.isfinite(min_score):
        body["minScore"] = min_score
    if recall_surface in ("explicit_api", "tool_call", "prompt_injection", "dashboard", "other"):
        body["recallSurface"] = recall_surface
    return body


def _normalize_loopback_host(host: str) -> str:
    """Use the daemon's IPv4 listener for IPv6-first local aliases."""
    normalized = host.strip().lower().strip("[]")
    if normalized in ("localhost", "::1", "0:0:0:0:0:0:0:1"):
        return _DEFAULT_HOST
    return host


def _format_host(host: str) -> str:
    """Format a hostname or IPv6 literal for an HTTP origin."""
    return host if host.startswith("[") or ":" not in host else f"[{host}]"


def _normalize_base_url(raw: str, source: str) -> str:
    """Normalize a daemon URL to an origin string."""
    parsed = urllib.parse.urlparse(raw)
    if parsed.scheme not in ("http", "https") or not parsed.netloc:
        raise ValueError(f"{source} must be an http(s) URL")
    if parsed.username or parsed.password:
        raise ValueError(f"{source} must not include username or password")
    if parsed.query or parsed.fragment:
        raise ValueError(f"{source} must not include query strings or fragments")
    if parsed.path not in ("", "/"):
        raise ValueError(f"{source} must point at the daemon origin, not a path")
    try:
        hostname = parsed.hostname
        port = parsed.port
    except ValueError as error:
        raise ValueError(f"{source} must be a valid HTTP origin") from error
    if not hostname:
        raise ValueError(f"{source} must include a hostname")
    normalized_host = _normalize_loopback_host(hostname)
    authority = _format_host(normalized_host)
    if port is not None:
        authority = f"{authority}:{port}"
    return urllib.parse.urlunparse((parsed.scheme, authority, "", "", "", ""))


def _resolve_base_url() -> str:
    """Resolve the Signet daemon base URL using the canonical loopback policy."""
    explicit = _sanitize(os.environ.get("SIGNET_DAEMON_URL", ""))
    if explicit:
        return _normalize_base_url(explicit, "SIGNET_DAEMON_URL")
    host = _normalize_loopback_host(_sanitize(os.environ.get("SIGNET_HOST", _DEFAULT_HOST)))
    port = _sanitize(os.environ.get("SIGNET_PORT", str(_DEFAULT_PORT)))
    return _normalize_base_url(f"http://{_format_host(host)}:{port}", "SIGNET_HOST/SIGNET_PORT")


def _is_loopback_host(host: str) -> bool:
    """Return true for localhost and loopback IP literals."""
    if host.lower() == "localhost":
        return True
    try:
        return ipaddress.ip_address(host).is_loopback
    except ValueError:
        return False


def _trusted_daemon_origins() -> List[str]:
    """Read the exact remote daemon origins trusted to receive SIGNET_TOKEN."""
    raw = _sanitize(os.environ.get(_TRUSTED_ORIGINS_ENV, ""))
    origins: List[str] = []
    for part in raw.split(","):
        candidate = part.strip()
        if not candidate:
            continue
        try:
            origins.append(_normalize_base_url(candidate, _TRUSTED_ORIGINS_ENV))
        except ValueError:
            continue
    return origins


def _should_send_auth_token(base_url: str) -> bool:
    """Only send bearer tokens to loopback or explicitly trusted daemon origins."""
    parsed = urllib.parse.urlparse(base_url)
    host = parsed.hostname or ""
    return _is_loopback_host(host) or base_url in _trusted_daemon_origins()


def _read_json_response(resp) -> Dict[str, Any]:
    """Read a daemon response, treating empty successful bodies as an empty object."""
    body = resp.read()
    if not body:
        return {}
    return json.loads(body.decode("utf-8"))


def _safe_score(value: Any) -> float:
    """Coerce daemon result scores without failing recall on malformed rows."""
    try:
        return float(value or 0.0)
    except (TypeError, ValueError):
        return 0.0


class SignetClient:
    """HTTP client for the Signet daemon API."""

    def __init__(self, agent_id: str = "", harness: str = "hermes-agent"):
        self._base_url = _resolve_base_url()
        self._agent_id = agent_id
        self._harness = harness

    @property
    def base_url(self) -> str:
        return self._base_url

    def _headers(self, extra: Optional[Dict[str, str]] = None) -> Dict[str, str]:
        h: Dict[str, str] = {
            "Content-Type": "application/json",
            "x-signet-runtime-path": "plugin",
            "x-signet-agent-id": self._agent_id,
            "x-signet-actor": "hermes-memory-plugin",
        }
        token = _sanitize(os.environ.get("SIGNET_API_KEY", "")) or _sanitize(os.environ.get("SIGNET_TOKEN", ""))
        if token and _should_send_auth_token(self._base_url):
            h["Authorization"] = f"Bearer {token}"
        if extra:
            h.update(extra)
        return h

    @staticmethod
    def _mutation_context_headers(
        *,
        session_id: str = "",
        request_id: str = "",
    ) -> Optional[Dict[str, str]]:
        """Build optional audit headers for a mirrored memory mutation."""
        headers: Dict[str, str] = {}
        clean_session_id = _sanitize(session_id)
        clean_request_id = _sanitize(request_id)
        if clean_session_id:
            headers["x-signet-session-id"] = clean_session_id
        if clean_request_id:
            headers["x-signet-request-id"] = clean_request_id
        return headers or None

    def _post(
        self,
        path: str,
        body: Dict[str, Any],
        *,
        timeout: float = _TIMEOUT_SECS,
        extra_headers: Optional[Dict[str, str]] = None,
    ) -> Optional[Dict[str, Any]]:
        """POST JSON to the daemon. Returns parsed response or None on failure."""
        url = f"{self._base_url}{path}"
        data = json.dumps(body).encode("utf-8")
        headers = self._headers(extra_headers)
        req = urllib.request.Request(url, data=data, headers=headers, method="POST")
        try:
            with urllib.request.urlopen(req, timeout=timeout) as resp:
                return _read_json_response(resp)
        except urllib.error.HTTPError as e:
            body_text = ""
            try:
                body_text = e.read().decode("utf-8", errors="replace")[:200]
            except Exception as read_err:
                logger.debug("Signet POST %s: failed to read error body: %s", path, read_err)
            logger.debug("Signet POST %s returned %d: %s", path, e.code, body_text)
            return None
        except (urllib.error.URLError, OSError, TimeoutError, ValueError) as e:
            logger.debug("Signet POST %s failed: %s", path, e)
            return None

    def _get(
        self,
        path: str,
        *,
        timeout: float = _TIMEOUT_SECS,
    ) -> Optional[Dict[str, Any]]:
        """GET from the daemon. Returns parsed response or None on failure."""
        url = f"{self._base_url}{path}"
        req = urllib.request.Request(url, headers=self._headers(), method="GET")
        try:
            with urllib.request.urlopen(req, timeout=timeout) as resp:
                return _read_json_response(resp)
        except (urllib.error.HTTPError, urllib.error.URLError, OSError, TimeoutError, ValueError) as e:
            logger.debug("Signet GET %s failed: %s", path, e)
            return None

    def _patch(
        self,
        path: str,
        body: Dict[str, Any],
        *,
        timeout: float = _TIMEOUT_SECS,
    ) -> Optional[Dict[str, Any]]:
        """PATCH JSON to the daemon. Returns parsed response or None on failure."""
        url = f"{self._base_url}{path}"
        data = json.dumps(body).encode("utf-8")
        req = urllib.request.Request(url, data=data, headers=self._headers(), method="PATCH")
        try:
            with urllib.request.urlopen(req, timeout=timeout) as resp:
                return _read_json_response(resp)
        except (urllib.error.HTTPError, urllib.error.URLError, OSError, TimeoutError, ValueError) as e:
            logger.debug("Signet PATCH %s failed: %s", path, e)
            return None

    def request_result(
        self,
        method: str,
        path: str,
        body: Optional[Dict[str, Any]] = None,
        *,
        timeout: float = _TIMEOUT_SECS,
    ) -> Dict[str, Any]:
        """Call the daemon and keep the failure reason: {ok, data} or {ok: False, status, error}."""
        url = f"{self._base_url}{path}"
        data = json.dumps(body).encode("utf-8") if body is not None else None
        req = urllib.request.Request(url, data=data, headers=self._headers(), method=method)
        try:
            with urllib.request.urlopen(req, timeout=timeout) as resp:
                try:
                    return {"ok": True, "data": _read_json_response(resp)}
                except ValueError as e:
                    return {"ok": False, "status": resp.status, "error": f"daemon returned invalid JSON: {e}"}
        except urllib.error.HTTPError as e:
            detail = ""
            try:
                raw = e.read().decode("utf-8", errors="replace")
                parsed = json.loads(raw) if raw else {}
                detail = str(parsed.get("error") or raw) if isinstance(parsed, dict) else raw
            except Exception as read_err:
                detail = f"unreadable error body: {read_err}"
            return {"ok": False, "status": e.code, "error": detail[:300] or f"HTTP {e.code}"}
        except (urllib.error.URLError, OSError, TimeoutError, ValueError) as e:
            return {"ok": False, "status": None, "error": f"daemon unreachable: {e}"}

    def _delete(
        self,
        path: str,
        *,
        timeout: float = _TIMEOUT_SECS,
        extra_headers: Optional[Dict[str, str]] = None,
    ) -> Optional[Dict[str, Any]]:
        """DELETE from the daemon. Returns parsed response or None on failure."""
        url = f"{self._base_url}{path}"
        req = urllib.request.Request(url, headers=self._headers(extra_headers), method="DELETE")
        try:
            with urllib.request.urlopen(req, timeout=timeout) as resp:
                return _read_json_response(resp)
        except (urllib.error.HTTPError, urllib.error.URLError, OSError, TimeoutError, ValueError) as e:
            logger.debug("Signet DELETE %s failed: %s", path, e)
            return None

    def is_available(self) -> bool:
        """Check if the Signet daemon is reachable. No credentials needed."""
        result = self._get("/health", timeout=2)
        return result is not None

    def session_start(
        self,
        session_key: str,
        *,
        project: str = "",
        claim_only: bool = False,
        context: Optional[Dict[str, Any]] = None,
    ) -> Optional[Dict[str, Any]]:
        """Call session-start hook, optionally recovering only the session claim."""
        body: Dict[str, Any] = {
            "harness": self._harness,
            "sessionKey": session_key,
            "project": project,
            "agentId": self._agent_id,
        }
        if claim_only:
            body["claimOnly"] = True
        if context:
            body["context"] = context
        return self._post(
            "/api/hooks/session-start",
            body,
            timeout=_LONG_TIMEOUT_SECS,
        )

    def user_prompt_submit(
        self,
        session_key: str,
        user_message: str,
        *,
        last_assistant_message: str = "",
        project: str = "",
        context: Optional[Dict[str, Any]] = None,
    ) -> Optional[Dict[str, Any]]:
        """Call user-prompt-submit hook. Returns recall inject text."""
        body: Dict[str, Any] = {
            "harness": self._harness,
            "sessionKey": session_key,
            "userMessage": user_message,
            "lastAssistantMessage": last_assistant_message,
            "agentId": self._agent_id,
            "project": project,
        }
        if context:
            body["context"] = context
        return self._post(
            "/api/hooks/user-prompt-submit",
            body,
            timeout=_RECALL_TIMEOUT_SECS,
        )

    def notifications(
        self,
        session_key: str,
        hook: str,
        *,
        project: str = "",
        context: Optional[Dict[str, Any]] = None,
    ) -> Optional[Dict[str, Any]]:
        """Fetch pending peer notifications for a compatible Hermes hook."""
        body: Dict[str, Any] = {
            "harness": self._harness,
            "hook": hook,
            "sessionKey": session_key,
            "agentId": self._agent_id,
            "project": project,
        }
        if context:
            body["context"] = context
        return self._post(
            "/api/hooks/notifications",
            body,
            timeout=_RECALL_TIMEOUT_SECS,
        )

    def wake(
        self,
        session_key: str,
        *,
        project: str = "",
        wait_ms: int = 25000,
        on_connection: Optional[Any] = None,
        context: Optional[Dict[str, Any]] = None,
    ) -> Optional[Dict[str, Any]]:
        """Long-poll the direct-message wake endpoint; None on transport failure."""
        parsed = urllib.parse.urlparse(self._base_url)
        host = parsed.hostname or _DEFAULT_HOST
        timeout = wait_ms / 1000 + 10
        factory = http.client.HTTPSConnection if parsed.scheme == "https" else http.client.HTTPConnection
        conn = factory(host, parsed.port, timeout=timeout)
        if on_connection:
            on_connection(conn)
        wake_body: Dict[str, Any] = {
            "harness": self._harness,
            "sessionKey": session_key,
            "agentId": self._agent_id,
            "project": project,
            "waitMs": wait_ms,
        }
        if context:
            wake_body["context"] = context
        body = json.dumps(wake_body)
        try:
            conn.request("POST", "/api/cross-agent/wake", body=body, headers=self._headers())
            resp = conn.getresponse()
            raw = resp.read()
            data = json.loads(raw.decode("utf-8")) if raw else {}
            if not isinstance(data, dict):
                return None
            if resp.status != 200 and "error" not in data:
                data["error"] = f"http {resp.status}"
            return data
        except (OSError, ValueError, http.client.HTTPException) as e:
            logger.debug("Signet wake failed: %s", e)
            return None
        finally:
            if on_connection:
                on_connection(None)
            try:
                conn.close()
            except OSError:
                pass

    def release_wake(self, session_key: str, message_ids: List[str]) -> Optional[Dict[str, Any]]:
        """Return claimed wakes to the daemon after the host refused delivery."""
        return self._post(
            "/api/cross-agent/wake/release",
            {"sessionKey": session_key, "agentId": self._agent_id, "messageIds": message_ids},
        )

    def session_end(
        self,
        session_key: str,
        transcript: str,
        *,
        project: str = "",
        reason: str = "",
    ) -> Optional[Dict[str, Any]]:
        """Call session-end hook. Triggers memory extraction from transcript."""
        body: Dict[str, Any] = {
            "harness": self._harness,
            "sessionKey": session_key,
            "transcript": transcript,
            "agentId": self._agent_id,
            "cwd": project,
        }
        if reason:
            body["reason"] = reason
        return self._post(
            "/api/hooks/session-end",
            body,
            timeout=_LONG_TIMEOUT_SECS,
        )

    def pre_compaction(
        self,
        session_key: str,
        *,
        session_context: str = "",
        message_count: int = 0,
    ) -> Optional[Dict[str, Any]]:
        """Call pre-compaction hook. Returns summary prompt and guidelines."""
        body: Dict[str, Any] = {
            "harness": self._harness,
            "sessionKey": session_key,
        }
        if session_context:
            body["sessionContext"] = session_context
        if message_count > 0:
            body["messageCount"] = message_count
        return self._post("/api/hooks/pre-compaction", body)

    def compaction_complete(
        self,
        session_key: str,
        summary: str,
        *,
        project: str = "",
    ) -> Optional[Dict[str, Any]]:
        """Call compaction-complete hook. Saves summary as session memory."""
        return self._post(
            "/api/hooks/compaction-complete",
            {
                "harness": self._harness,
                "sessionKey": session_key,
                "summary": summary,
                "agentId": self._agent_id,
                "project": project,
            },
            timeout=_LONG_TIMEOUT_SECS,
        )

    def checkpoint_extract(
        self,
        session_key: str,
        transcript: str,
        *,
        project: str = "",
    ) -> Optional[Dict[str, Any]]:
        """Call checkpoint-extract for long-running sessions.

        Extracts only the delta since last extraction. Does not
        release the session claim.
        """
        return self._post(
            "/api/hooks/session-checkpoint-extract",
            {
                "harness": self._harness,
                "sessionKey": session_key,
                "transcript": transcript,
                "agentId": self._agent_id,
                "project": project,
            },
            timeout=_LONG_TIMEOUT_SECS,
        )

    def remember(
        self,
        content: str,
        *,
        importance: float = 0.5,
        tags: Optional[List[str]] = None,
        memory_type: str = "",
        pinned: Optional[bool] = None,
        project: str = "",
        source_type: str = "",
        source_id: str = "",
        hints: Optional[List[str]] = None,
        transcript: str = "",
        structured: Optional[Dict[str, Any]] = None,
        review_after: str = "",
        who: str = "hermes-agent",
        visibility: str = "",
        supersedes: str = "",
        reason: str = "",
        idempotency_key: str = "",
        session_id: str = "",
        request_id: str = "",
    ) -> Optional[Dict[str, Any]]:
        """Store a memory via the daemon API."""
        body: Dict[str, Any] = {
            "content": content,
            "importance": importance,
            "who": who,
        }
        if self._agent_id:
            body["agentId"] = self._agent_id
        if memory_type:
            body["type"] = memory_type
        if tags:
            body["tags"] = tags
        if pinned is not None:
            body["pinned"] = pinned
        if project:
            body["project"] = project
        if source_type:
            body["sourceType"] = source_type
        if source_id:
            body["sourceId"] = source_id
        if hints:
            body["hints"] = hints
        if transcript:
            body["transcript"] = transcript
        if structured:
            body["structured"] = structured
        if review_after:
            body["reviewAfter"] = review_after
        if visibility in {"global", "private", "archived"}:
            body["visibility"] = visibility
        if supersedes:
            body["supersedes"] = supersedes
        if reason:
            body["reason"] = reason
        if idempotency_key:
            body["idempotencyKey"] = idempotency_key
        context_headers = self._mutation_context_headers(session_id=session_id, request_id=request_id)
        if context_headers:
            return self._post(
                "/api/memory/remember",
                body,
                timeout=_LONG_TIMEOUT_SECS,
                extra_headers=context_headers,
            )
        return self._post("/api/memory/remember", body, timeout=_LONG_TIMEOUT_SECS)

    def recall(
        self,
        query: str,
        *,
        limit: Any = None,
        project: str = "",
        memory_type: str = "",
        tags: str = "",
        who: str = "",
        pinned: Optional[bool] = None,
        importance_min: Optional[float] = None,
        since: str = "",
        until: str = "",
        keyword_query: str = "",
        score_min: Optional[float] = None,
        aggregate: bool = False,
        aggregate_budget: str = "",
        save_aggregate: Optional[bool] = None,
        agent_scoped: bool = False,
    ) -> Optional[Dict[str, Any]]:
        """Search memories via hybrid recall."""
        body = _build_recall_request_body(
            query,
            limit=limit,
            project=project,
            memory_type=memory_type,
            tags=tags,
            who=who,
            pinned=pinned,
            importance_min=importance_min,
            since=since,
            until=until,
            keyword_query=keyword_query,
            aggregate=aggregate,
            aggregate_budget=aggregate_budget,
            save_aggregate=save_aggregate,
            min_score=score_min,
            agent_id=self._agent_id if agent_scoped else "",
            recall_surface="tool_call",
        )

        result = self._post("/api/memory/recall", body, timeout=_RECALL_TIMEOUT_SECS)
        if (
            result
            and score_min is not None
            and isinstance(result.get("results"), list)
        ):
            kept = [
                row for row in result["results"]
                if not isinstance(row, dict) or _safe_score(row.get("score")) >= score_min
            ]
            result = dict(result)
            result["results"] = kept
            meta = result.get("meta")
            if isinstance(meta, dict):
                result["meta"] = {**meta, "totalReturned": len(kept), "noHits": len(kept) == 0}
        return result

    def session_search(
        self,
        query: str,
        *,
        session_key: str = "",
        current_session_key: str = "",
        agent_id: str = "",
        project: str = "",
        limit: int = 10,
    ) -> Optional[Dict[str, Any]]:
        """Search active or completed session transcripts."""
        body: Dict[str, Any] = {
            "query": query,
            "limit": limit,
        }
        if session_key:
            body["sessionKey"] = session_key
        if current_session_key:
            body["currentSessionKey"] = current_session_key
        resolved_agent_id = agent_id or self._agent_id
        if resolved_agent_id:
            body["agentId"] = resolved_agent_id
        if project:
            body["project"] = project
        return self._post("/api/sessions/search", body, timeout=_RECALL_TIMEOUT_SECS)

    def get_memory(self, memory_id: str) -> Optional[Dict[str, Any]]:
        """Retrieve a single memory by ID."""
        return self._get(f"/api/memory/{urllib.parse.quote(memory_id)}")

    def list_memories(
        self,
        *,
        limit: int = 100,
        offset: int = 0,
        memory_type: str = "",
    ) -> Optional[Dict[str, Any]]:
        """List memories with optional filters."""
        params = f"?limit={limit}&offset={offset}"
        if memory_type:
            params += f"&type={urllib.parse.quote(memory_type)}"
        return self._get(f"/api/memories{params}")

    def modify_memory(
        self,
        memory_id: str,
        *,
        content: str = "",
        memory_type: str = "",
        importance: Optional[float] = None,
        tags: str = "",
        pinned: Optional[bool] = None,
        reason: str,
    ) -> Optional[Dict[str, Any]]:
        """Edit an existing memory by ID."""
        body: Dict[str, Any] = {"reason": reason}
        if content:
            body["content"] = content
        if memory_type:
            body["type"] = memory_type
        if importance is not None:
            body["importance"] = importance
        if tags:
            body["tags"] = tags
        if pinned is not None:
            body["pinned"] = pinned
        return self._patch(f"/api/memory/{urllib.parse.quote(memory_id)}", body)

    def forget_memory(
        self,
        memory_id: str,
        *,
        reason: str,
        session_id: str = "",
        request_id: str = "",
    ) -> Optional[Dict[str, Any]]:
        """Soft-delete a memory by ID."""
        params = urllib.parse.urlencode({"reason": reason})
        path = f"/api/memory/{urllib.parse.quote(memory_id, safe='')}?{params}"
        context_headers = self._mutation_context_headers(session_id=session_id, request_id=request_id)
        if context_headers:
            return self._delete(path, extra_headers=context_headers)
        return self._delete(path)

    def supersede_memory(
        self,
        memory_id: str,
        superseded_by: str,
        *,
        reason: str,
        session_id: str = "",
        request_id: str = "",
    ) -> Optional[Dict[str, Any]]:
        """Mark one memory as superseded by another in an audited transaction."""
        path = f"/api/memories/{urllib.parse.quote(memory_id, safe='')}/supersede"
        body = {
            "superseded_by": superseded_by,
            "reason": reason,
        }
        context_headers = self._mutation_context_headers(session_id=session_id, request_id=request_id)
        if context_headers:
            return self._post(path, body, extra_headers=context_headers)
        return self._post(path, body)

    def search(
        self,
        query: str,
        *,
        limit: int = 10,
        memory_type: str = "",
        tags: str = "",
        project: str = "",
    ) -> List[Dict[str, Any]]:
        """Search memories. Returns list of memory objects."""
        params = f"?q={urllib.parse.quote(query, safe='')}&limit={limit}"
        if memory_type:
            params += f"&type={urllib.parse.quote(memory_type, safe='')}"
        if tags:
            params += f"&tags={urllib.parse.quote(tags, safe='')}"
        if project:
            params += f"&project={urllib.parse.quote(project, safe='')}"
        result = self._get(f"/api/memory/search{params}")
        if result and isinstance(result, dict):
            return result.get("results", result.get("memories", []))
        if isinstance(result, list):
            return result
        return []

    def feedback(
        self,
        ratings: Dict[str, float],
        *,
        session_key: str = "",
    ) -> Optional[Dict[str, Any]]:
        """Rate memory relevance for predictor training."""
        body: Dict[str, Any] = {"ratings": ratings}
        if session_key:
            body["session_key"] = session_key
        return self._post("/api/memory/feedback", body)
