"""Memory Factory - 内存工厂：创建带有可选向量搜索功能的 MemoryStore"""

from __future__ import annotations

from pathlib import Path
from typing import TYPE_CHECKING

from loguru import logger

if TYPE_CHECKING:
    from miobot.config.schema import Config
    from miobot.agent.memory import MemoryStore


def create_memory_store(config: Config, workspace: Path) -> "MemoryStore":
    """创建带有可选向量存储的 MemoryStore，用于语义搜索

    Args:
        config: 应用配置对象
        workspace: 工作区目录路径

    Returns:
        MemoryStore 实例，可能包含向量存储功能
    """
    from miobot.agent.memory import MemoryStore
    from miobot.agent.embedding import create_embedding_provider
    from miobot.agent.vector_store import VectorStore

    # 检查是否启用了向量搜索功能
    if not config.memory.enabled:
        logger.info("向量记忆已禁用，使用基于文件的简单记忆")
        return MemoryStore(workspace)

    # 尝试初始化向量存储
    vector_store = None
    try:
        embedding_provider = create_embedding_provider(
            provider=config.memory.embedding_provider,
            api_key=config.memory.api_key
            or _get_provider_api_key(config, config.memory.embedding_provider),
            model=config.memory.embedding_model,
        )

        vector_store = VectorStore(
            workspace=workspace,
            embedding_provider=embedding_provider,
            collection_name="chat_memory",
        )

        logger.info(
            "Vector memory enabled: provider={}, model={}, dimension={}",
            config.memory.embedding_provider,
            config.memory.embedding_model,
            embedding_provider.dimension,
        )

    except ImportError as e:
        logger.warning(
            "Vector memory dependencies not installed, falling back to simple memory: {}", e
        )
    except Exception:
        logger.exception("Failed to initialize vector store, falling back to simple memory")

    return MemoryStore(workspace, vector_store)


def _get_provider_api_key(config: Config, provider: str) -> str | None:
    """从 provider 配置中获取 API 密钥

    Args:
        config: 应用配置对象
        provider: provider 名称（如 openai、dashscope）

    Returns:
        API 密钥字符串，如果未找到则返回 None
    """
    provider = provider.lower()

    if provider == "openai":
        return config.providers.openai.api_key
    elif provider == "dashscope":
        return config.providers.dashscope.api_key

    return None
