"""Diagnostic checks: Roo Code / Cline configuration."""
from __future__ import annotations

import asyncio
import json
import shutil
import subprocess
from pathlib import Path
from typing import Any



async def check_roo_cline_config() -> dict[str, Any]:
    """Check if Roo Code is configured in VS Code settings."""
    vscode_user_dir = Path.home() / ".local" / "share" / "code-server" / "User"
    settings_file = vscode_user_dir / "settings.json"

    result = {
        "service": "roo_cline",
        "settings_file_exists": False,
        "configured": False,
        "api_provider": None,
        "base_url": None,
        "details": {},
    }

    data: dict[str, Any] | None = None

    if settings_file.exists():
        result["settings_file_exists"] = True
        try:
            data = json.loads(settings_file.read_text())
        except Exception as e:
            result["details"]["error"] = str(e)

    if data is None:
        docker_bin = shutil.which("docker")
        if docker_bin:
            try:
                proc = await asyncio.to_thread(
                    subprocess.run,
                    [
                        "docker",
                        "exec",
                        "proxym-vscode",
                        "cat",
                        "/home/coder/.local/share/code-server/User/settings.json",
                    ],
                    capture_output=True,
                    text=True,
                    timeout=10,
                )
                if proc.returncode == 0 and proc.stdout.strip():
                    result["settings_file_exists"] = True
                    data = json.loads(proc.stdout)
                elif proc.returncode != 0:
                    result["details"]["docker_error"] = proc.stderr.strip()
            except Exception as e:
                result["details"]["docker_error"] = str(e)
        else:
            result["status"] = "skipped"
            result["details"]["skipped"] = "settings.json not found and docker not on PATH"
            return result

    if data is not None:
        result["api_provider"] = data.get("roo-cline.apiProvider")
        result["base_url"] = data.get("roo-cline.openAiBaseUrl")
        result["configured"] = (
            result["api_provider"] == "openai" and bool(result["base_url"]) and bool(data.get("roo-cline.openAiApiKey"))
        )
        result["details"]["model_id"] = data.get("roo-cline.openAiModelId")
        result["details"]["custom_modes_count"] = len(data.get("roo-cline.customModes", []))
        result["details"]["has_api_key"] = bool(data.get("roo-cline.openAiApiKey"))
        modes = data.get("roo-cline.modeApiConfigs", {})
        result["details"]["mode_configs"] = list(modes.keys()) if modes else []
        mcp = data.get("roo-cline.mcpServers", {})
        result["details"]["mcp_servers"] = list(mcp.keys()) if mcp else []
        result["details"]["workspace_trust_disabled"] = data.get("security.workspace.trust.enabled") is False
        result["details"]["color_theme"] = data.get("workbench.colorTheme")

    return result
