"""Tests for Roo Code diagnostics."""

from __future__ import annotations

import json
from pathlib import Path

import pytest

import proxym.api._diag_roo as diag_roo


def _write_valid_settings(path: Path) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    base_url = "http://proxy:4000/v1"
    api_key = "sk-test"
    settings = {
        "roo-cline.apiProvider": "openai",
        "roo-cline.openAiBaseUrl": base_url,
        "roo-cline.openAiApiKey": api_key,
        "roo-cline.openAiModelId": "balanced",
        "roo-cline.modeApiConfigs": {
            "code": {
                "apiProvider": "openai",
                "openAiBaseUrl": base_url,
                "openAiApiKey": api_key,
                "openAiModelId": "balanced",
            },
            "architect": {
                "apiProvider": "openai",
                "openAiBaseUrl": base_url,
                "openAiApiKey": api_key,
                "openAiModelId": "free",
            },
            "debug": {
                "apiProvider": "openai",
                "openAiBaseUrl": base_url,
                "openAiApiKey": api_key,
                "openAiModelId": "cheap",
            },
            "ask": {
                "apiProvider": "openai",
                "openAiBaseUrl": base_url,
                "openAiApiKey": api_key,
                "openAiModelId": "free",
            },
        },
        "roo-cline.mcpServers": {
            "proxym": {
                "url": "http://proxy:4000",
            }
        },
        "roo-cline.customModes": [],
        "security.workspace.trust.enabled": False,
        "workbench.colorTheme": "Default Dark Modern",
    }
    path.write_text(json.dumps(settings), encoding="utf-8")


@pytest.mark.asyncio
async def test_check_roo_cline_config_prefers_existing_settings_candidate(monkeypatch, tmp_path):
    """The diagnostics should read the mounted settings.json fallback when present."""
    missing_candidate = tmp_path / "home" / ".local" / "share" / "code-server" / "User" / "settings.json"
    mounted_candidate = tmp_path / "app" / "vscode-user-data" / "settings.json"
    _write_valid_settings(mounted_candidate)

    monkeypatch.setattr(diag_roo, "_SETTINGS_CANDIDATES", [missing_candidate, mounted_candidate])

    result = await diag_roo.check_roo_cline_config()

    assert result["settings_file_exists"] is True
    assert result["configured"] is True
    assert result["api_provider"] == "openai"
    assert result["base_url"] == "http://proxy:4000/v1"
    assert result["details"]["settings_source"] == str(mounted_candidate)
    assert result["details"]["has_api_key"] is True
    assert set(result["details"]["mode_configs"]) == {"code", "architect", "debug", "ask"}
    assert result["details"]["mcp_servers"] == ["proxym"]
    assert result["details"]["workspace_trust_disabled"] is True


@pytest.mark.asyncio
async def test_check_roo_cline_config_skips_when_no_settings_and_no_docker(monkeypatch, tmp_path):
    """When no settings are present and Docker is unavailable, diagnostics should skip cleanly."""
    missing_candidate = tmp_path / "missing" / "settings.json"
    monkeypatch.setattr(diag_roo, "_SETTINGS_CANDIDATES", [missing_candidate])
    monkeypatch.setattr(diag_roo.shutil, "which", lambda *_: None)

    result = await diag_roo.check_roo_cline_config()

    assert result["status"] == "skipped"
    assert result["settings_file_exists"] is False
    assert result["details"]["skipped"] == diag_roo._SETTINGS_NOT_FOUND_DOCKER_MISSING
