"""Bridge module providing a singleton MemorySystem for GreyMatter.

Lazily initializes a cognitive MemorySystem configured with Ollama
embeddings when available, falling back to keyword-only mode otherwise.
"""

import logging
import os
from typing import Optional

import httpx
from cognitive import MemorySystem

logger = logging.getLogger(__name__)

_instance: Optional[MemorySystem] = None

OLLAMA_URL = os.environ.get("GM_OLLAMA_URL", "http://localhost:11434/api/embeddings")
EMBED_MODEL = os.environ.get("GM_EMBED_MODEL", "nomic-embed-text")
EMBED_DIM = int(os.environ.get("GM_EMBED_DIM", "768"))
DEFAULT_DB_PATH = os.environ.get("GM_DB_PATH", "~/.greymatter/greymatter.db")


def ollama_embed(text: str) -> list[float]:
    """Generate embeddings via Ollama's nomic-embed-text model.

    Args:
        text: The text to embed.

    Returns:
        A list of 768 floats representing the embedding vector.

    Raises:
        httpx.HTTPError: If the Ollama server is unreachable.
    """
    response = httpx.post(
        OLLAMA_URL,
        json={"model": EMBED_MODEL, "prompt": text},
        timeout=5,
    )
    response.raise_for_status()
    return response.json()["embedding"]


def get_memory(db_path: Optional[str] = None) -> MemorySystem:
    """Return the singleton MemorySystem instance.

    On first call, creates the instance with Ollama embeddings if
    the server is reachable, otherwise falls back to keyword-only mode.

    Args:
        db_path: Path to the SQLite database. Defaults to
            ``~/.greymatter/greymatter.db``.

    Returns:
        The shared MemorySystem instance.
    """
    global _instance
    if _instance is not None:
        return _instance

    if db_path is None:
        db_path = DEFAULT_DB_PATH

    embed_fn = None
    embed_dim = EMBED_DIM

    try:
        # Probe Ollama to verify connectivity
        ollama_embed("ping")
        embed_fn = ollama_embed
    except Exception:
        logger.warning(
            "Ollama unreachable at %s; falling back to keyword-only mode",
            OLLAMA_URL,
        )

    _instance = MemorySystem(
        db_path=db_path,
        license_key="greymatter",
        embed_fn=embed_fn,
        embed_dim=embed_dim,
    )
    return _instance


def reset() -> None:
    """Clear the singleton instance. Intended for testing."""
    global _instance
    _instance = None
