import shutil

import requests
from fastapi import APIRouter, Request

from backend.config import (
    GOOGLE_API_SUPPORT,
    LLAMACPP_URL,
    MCP_SUPPORT,
    OUTLOOK_SUPPORT,
    PDF_SUPPORT,
    _mcp_command_available,
    _resolve_mcp_command,
    _load_settings,
    get_playwright_status,
)
from backend.models import (
    _model_cache,
    get_all_models,
    get_ollama_library,
    get_ollama_models,
    ollama_delete_model,
    ollama_pull_model,
    ollama_pull_status,
)


router = APIRouter()
DDG_SUPPORT = True  # Bing RSS + Wikipedia combo (no extra packages needed)


@router.get("/api/models")
def api_get_models(refresh: bool = False):
    if refresh:
        _model_cache.clear()
    return {"models": get_all_models()}


@router.get("/api/ollama/library")
def api_ollama_library():
    return {"ok": True, "models": get_ollama_library()}


@router.post("/api/ollama/pull")
async def api_ollama_pull(request: Request):
    body = await request.json()
    model = (body.get("model") or "").strip()
    if not model:
        return {"ok": False, "error": "Missing model name"}
    return ollama_pull_model(model)


@router.get("/api/ollama/pull/status")
def api_ollama_pull_status(model: str = ""):
    return ollama_pull_status(model or None)


@router.get("/api/ollama/installed")
def api_ollama_installed():
    return {"ok": True, "models": get_ollama_models()}


@router.post("/api/ollama/delete")
async def api_ollama_delete(request: Request):
    body = await request.json()
    model = (body.get("model") or "").strip()
    if not model:
        return {"ok": False, "error": "Missing model name"}
    return ollama_delete_model(model)


@router.get("/api/capabilities")
def api_capabilities():
    settings = _load_settings()
    browser_status = get_playwright_status()
    uvx_available = bool(shutil.which("uvx"))
    node_available = _mcp_command_available("node")
    npm_available = _mcp_command_available("npm")
    npx_available = _mcp_command_available("npx")
    brave_configured = bool((settings.get("brave_api_key", "") or "").strip())
    ollama_cloud_configured = bool((settings.get("ollama_cloud_api_key", "") or "").strip())
    nvidia_configured = bool((settings.get("nvidia_api_key", "") or "").strip())
    openai_configured = bool((settings.get("openai_api_key", "") or "").strip())
    gemini_configured = bool((settings.get("gemini_api_key", "") or "").strip())
    llamacpp_running = False
    try:
        lc_url = (settings.get("llamacpp_url") or LLAMACPP_URL).rstrip("/")
        response = requests.get(f"{lc_url}/v1/models", timeout=2)
        llamacpp_running = response.status_code == 200
    except Exception:
        pass
    return {
        "pdf": PDF_SUPPORT,
        "web_search": DDG_SUPPORT,
        "brave_search": brave_configured,
        "ollama_cloud": ollama_cloud_configured,
        "nvidia": nvidia_configured,
        "openai": openai_configured,
        "gemini": gemini_configured,
        "llamacpp": llamacpp_running,
        "outlook": OUTLOOK_SUPPORT,
        "google_api": GOOGLE_API_SUPPORT,
        "browser": bool(browser_status.get("available")),
        "browser_package_installed": bool(browser_status.get("package_installed")),
        "browser_chromium_installed": bool(browser_status.get("chromium_installed")),
        "browser_detail": str(browser_status.get("detail") or "").strip(),
        "mcp": MCP_SUPPORT,
        "uvx": uvx_available,
        "node": node_available,
        "npm": npm_available,
        "npx": npx_available,
        "node_path": _resolve_mcp_command("node") if node_available else "",
        "npm_path": _resolve_mcp_command("npm") if npm_available else "",
        "npx_path": _resolve_mcp_command("npx") if npx_available else "",
    }