"""MidOS MCP server configuration and path resolution."""

import os
from pathlib import Path

# --- Path Resolution ---
# Priority: MIDOS_ROOT env var > auto-detect from package location > cwd
_MIDOS_ROOT_ENV = os.getenv("MIDOS_ROOT", "")


def resolve_midos_root() -> Path:
    """Resolve the MidOS project root directory.

    Resolution order:
    1. MIDOS_ROOT environment variable (explicit override)
    2. Auto-detect: walk up from this file looking for CLAUDE.md + knowledge/
    3. Fallback: current working directory
    """
    if _MIDOS_ROOT_ENV:
        root = Path(_MIDOS_ROOT_ENV)
        if root.is_dir():
            return root.resolve()

    # Auto-detect: this file is in midos-mcp/midos_mcp/config.py
    # MidOS root would be at ../.. if running from the monorepo
    candidate = Path(__file__).parent.parent.parent
    if (candidate / "CLAUDE.md").exists() and (candidate / "knowledge").is_dir():
        return candidate.resolve()

    # Fallback: cwd
    cwd = Path.cwd()
    if (cwd / "CLAUDE.md").exists() and (cwd / "knowledge").is_dir():
        return cwd.resolve()

    return cwd.resolve()


MIDOS_ROOT = resolve_midos_root()

# --- Knowledge paths ---
KNOWLEDGE_DIR = MIDOS_ROOT / "knowledge"
CHUNKS_DIR = KNOWLEDGE_DIR / "chunks"
SKILLS_DIR = KNOWLEDGE_DIR / "skills"
EUREKA_DIR = KNOWLEDGE_DIR / "EUREKA"
TRUTH_DIR = KNOWLEDGE_DIR / "truth"
SOTA_DIR = KNOWLEDGE_DIR / "SOTA"
PROTOCOLS_DIR = MIDOS_ROOT / "docs"

# --- Server defaults ---
DEFAULT_HOST = os.getenv("MIDOS_HOST", "127.0.0.1")
DEFAULT_PORT = int(os.getenv("MIDOS_PORT", "8419"))
DEFAULT_TRANSPORT = os.getenv("MIDOS_TRANSPORT", "stdio")

# --- API key config ---
CONFIG_DIR = MIDOS_ROOT / "config"
API_KEYS_FILE = CONFIG_DIR / "api_keys.json"
API_USAGE_FILE = CONFIG_DIR / "api_usage.json"

# --- Version ---
VERSION = "1.0.0"
SERVER_NAME = "midos"
