"""Handler factory — create the correct handler based on config."""
from __future__ import annotations

import logging
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from trustmem.config import TrustMemConfig
    from trustmem.handler.protocol import HandlerProtocol

logger = logging.getLogger(__name__)


def create_handler(config: "TrustMemConfig") -> "HandlerProtocol":
    """Create a handler instance based on config.handler_mode.

    Args:
        config: TrustMem configuration

    Returns:
        A handler implementing HandlerProtocol
    """
    if config.handler_mode == "persistent":
        from trustmem.handler.persistent import PersistentHandler
        from trustmem.ai import create_ai_client

        # VectorStore: "sqlite" or "" → auto-fallback in PersistentHandler
        vs = None
        if config.vector_store not in ("sqlite", ""):
            from trustmem.vectorstore import create_vectorstore

            vs_kwargs: dict = {}
            if config.vector_store == "qdrant":
                if not config.qdrant_url:
                    logger.warning(
                        "QDRANT_URL not set — using default http://localhost:6333. "
                        "Set it with: export QDRANT_URL=http://your-qdrant:6333"
                    )
                vs_kwargs = dict(
                    url=config.qdrant_url,
                    api_key=config.qdrant_api_key,
                    collection_name=config.qdrant_collection,
                    vector_size=config.embed_dim,
                )
            try:
                vs = create_vectorstore(backend=config.vector_store, **vs_kwargs)
            except Exception as e:
                raise RuntimeError(
                    f"Failed to initialize vector store '{config.vector_store}': {e}\n"
                    f"  - For qdrant: ensure Qdrant is running at {config.qdrant_url}\n"
                    f"  - For sqlite: use --vector-store sqlite (default)"
                ) from e

        ai = create_ai_client(
            provider=config.embed_provider,
            api_key=config.openai_api_key,
            base_url=config.openai_base_url or None,
            embed_model=config.embed_model,
            llm_model=config.llm_model,
        )

        # GraphStore: "sqlite" or "" → auto-fallback in PersistentHandler
        gs = None
        if config.graph_store not in ("sqlite", ""):
            if config.graph_store == "neo4j" and not config.neo4j_password:
                logger.warning(
                    "NEO4J_PASSWORD not set — Neo4j connection may fail.\n"
                    "  Set it with: export NEO4J_PASSWORD=your-password"
                )
            from trustmem.graphstore import create_graphstore

            try:
                gs = create_graphstore(
                    backend=config.graph_store,
                    uri=config.neo4j_uri,
                    auth=(config.neo4j_user, config.neo4j_password),
                    database=config.neo4j_database,
                )
            except Exception as e:
                raise RuntimeError(
                    f"Failed to initialize graph store '{config.graph_store}': {e}\n"
                    f"  - For neo4j: ensure Neo4j is running at {config.neo4j_uri}\n"
                    f"  - For in-memory: use --graph-store memory"
                ) from e

        return PersistentHandler(
            database_url=config.database_url,
            vectorstore=vs,
            ai_client=ai,
            graphstore=gs,
            read_audit=config.read_audit,
        )
    else:
        raise ValueError(
            f"Unknown handler_mode: '{config.handler_mode}'\n"
            f"  Valid modes: persistent\n"
            f"  Set with: export HANDLER_MODE=persistent"
        )
