"""Velixar memory module for LangChain."""

from typing import Any, Dict, List, Optional

import httpx
from langchain_core.memory import BaseMemory
from pydantic import Field

from ._http import create_client, request_with_retry


class VelixarMemory(BaseMemory):
    """Persistent cross-session memory backed by Velixar AI.

    Example:
        from velixar_langchain import VelixarMemory

        memory = VelixarMemory(
            api_key="vx_...",
            workspace_id="ws_abc123",
            user_id="user_1",
        )
    """

    api_key: str
    workspace_id: str
    user_id: str = ""
    base_url: str = "https://api.velixarai.com"
    memory_key: str = "velixar_context"
    top_k: int = 5
    _client: Optional[httpx.Client] = None

    class Config:
        arbitrary_types_allowed = True
        underscore_attrs_are_private = True

    @property
    def memory_variables(self) -> List[str]:
        return [self.memory_key]

    def _get_client(self) -> httpx.Client:
        if self._client is None:
            self._client = create_client(self.base_url, self.api_key)
        return self._client

    def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, str]:
        query = inputs.get("input", inputs.get("question", ""))
        if not query:
            return {self.memory_key: ""}

        resp = request_with_retry(
            self._get_client(), "GET", "/v1/memory/search",
            params={
                "q": query,
                "workspace_id": self.workspace_id,
                "limit": self.top_k,
            },
        )
        if resp.status_code != 200:
            return {self.memory_key: ""}

        memories = resp.json().get("memories", [])
        context = "\n".join(m.get("content", "") for m in memories)
        return {self.memory_key: context}

    def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None:
        content = outputs.get("output", outputs.get("text", ""))
        if not content:
            return

        request_with_retry(
            self._get_client(), "POST", "/v1/memory",
            json={
                "content": content,
                "workspace_id": self.workspace_id,
                "user_id": self.user_id,
                "tags": ["langchain", "auto"],
            },
        )

    def clear(self) -> None:
        pass  # Velixar memories are persistent by design
