"""Dynamic tab completion with short-TTL cosmetic cache.

Tab completion is the ONLY feature that caches discovery data. Functional
commands always query live. Cache TTL is 60 seconds.
"""

import json
import logging
import time
from pathlib import Path

from mcpbundles.config import CONFIG_DIR

logger = logging.getLogger(__name__)

CACHE_FILE = CONFIG_DIR / "completion_cache.json"
CACHE_TTL_SECONDS = 60


def _load_cache() -> dict | None:
    if not CACHE_FILE.exists():
        return None
    try:
        data = json.loads(CACHE_FILE.read_text())
        if time.time() - data.get("ts", 0) > CACHE_TTL_SECONDS:
            return None
        return data
    except Exception:
        return None


def _save_cache(tool_names: list[str], resource_uris: list[str], prompt_names: list[str]) -> None:
    try:
        CONFIG_DIR.mkdir(parents=True, exist_ok=True)
        data = {
            "ts": time.time(),
            "tools": tool_names,
            "resources": resource_uris,
            "prompts": prompt_names,
        }
        CACHE_FILE.write_text(json.dumps(data))
    except Exception:
        pass


def update_cache(tool_names: list[str], resource_uris: list[str], prompt_names: list[str]) -> None:
    _save_cache(tool_names, resource_uris, prompt_names)


def get_tool_names() -> list[str]:
    cache = _load_cache()
    if cache:
        return cache.get("tools", [])
    return []


def get_resource_uris() -> list[str]:
    cache = _load_cache()
    if cache:
        return cache.get("resources", [])
    return []


def get_prompt_names() -> list[str]:
    cache = _load_cache()
    if cache:
        return cache.get("prompts", [])
    return []


def get_connection_names() -> list[str]:
    """Load named connections for tab completion."""
    from mcpbundles.connections import ConnectionManager
    mgr = ConnectionManager()
    return [c.name for c in mgr.list_connections()]


def tool_name_completer(ctx, param, incomplete: str) -> list[str]:
    """Click shell completion for tool names."""
    names = get_tool_names()
    return [n for n in names if n.startswith(incomplete)]


def resource_uri_completer(ctx, param, incomplete: str) -> list[str]:
    """Click shell completion for resource URIs."""
    uris = get_resource_uris()
    return [u for u in uris if u.startswith(incomplete)]


def prompt_name_completer(ctx, param, incomplete: str) -> list[str]:
    """Click shell completion for prompt names."""
    names = get_prompt_names()
    return [n for n in names if n.startswith(incomplete)]


def connection_name_completer(ctx, param, incomplete: str) -> list[str]:
    """Click shell completion for connection names."""
    names = get_connection_names()
    return [n for n in names if n.startswith(incomplete)]
