"""Configuration for the Neo Cortex server."""

import os
from pathlib import Path


def load_api_key(name: str) -> str:
    """Load an API key from env var or ~/.accounts file.

    Priority: env var (JINA_API_KEY, GROQ_API_KEY) → ~/.accounts (name:key)
    """
    env_var = f"{name.upper()}_API_KEY"
    env_val = os.environ.get(env_var)
    if env_val:
        return env_val

    accounts_path = Path.home() / ".accounts"
    if accounts_path.exists():
        for line in accounts_path.read_text().strip().splitlines():
            if line.startswith(f"{name}:"):
                return line.split(":", 1)[1].strip()

    raise KeyError(f"Key '{name}' not found in ${env_var} or ~/.accounts")


# Paths
CORTEX_DB_PATH = os.environ.get(
    "CORTEX_DB_PATH",
    str(Path.home() / "neo-ram" / "cortex_db"),
)
COLLECTION_NAME = os.environ.get("CORTEX_COLLECTION", "conversations_v2")

# Server
CORTEX_PORT = int(os.environ.get("CORTEX_PORT", "5074"))
CORTEX_HOST = os.environ.get("CORTEX_HOST", "0.0.0.0")

# Memory index (SQLite + FTS5)
MEMORY_INDEX_DB_PATH = os.environ.get(
    "MEMORY_INDEX_DB_PATH",
    str(Path.home() / "neo-ram" / "cortex_db" / "memory_index.db"),
)

# Conversation log
CONVERSATION_DB_PATH = os.environ.get(
    "CONVERSATION_DB_PATH",
    str(Path.home() / "neo-ram" / "cortex_db" / "conversation_log.db"),
)

# Jina
JINA_MODEL = "jina-embeddings-v3"
JINA_DIMENSIONS = 1024
JINA_URL = "https://api.jina.ai/v1/embeddings"

# Groq
GROQ_MODEL = "llama-3.3-70b-versatile"
GROQ_URL = "https://api.groq.com/openai/v1/chat/completions"
