# Copyright (C) 2026 GoodData Corporation

"""Detection helpers for existing onboarding/client config."""

from __future__ import annotations

import tomllib
from pathlib import Path
from typing import cast

import orjson


def mcp_json_has_aida_server(mcp_json_path: Path) -> bool:
    """Return True when mcp.json already contains `mcpServers.aida`."""

    if not mcp_json_path.exists():
        return False
    try:
        loaded: object = orjson.loads(mcp_json_path.read_text(encoding="utf-8"))
        if not isinstance(loaded, dict):
            return False
        data = cast(dict[str, object], loaded)
        servers_raw: object = data.get("mcpServers")
        if not isinstance(servers_raw, dict):
            return False
        servers = cast(dict[str, object], servers_raw)
        return isinstance(servers.get("aida"), dict)
    except Exception:
        return False


def codex_toml_has_aida_server(codex_config_path: Path) -> bool:
    """Return True when Codex config.toml already contains mcp_servers.aida."""

    if not codex_config_path.exists():
        return False
    try:
        loaded = tomllib.loads(codex_config_path.read_text(encoding="utf-8"))
        if not isinstance(loaded, dict):
            return False
        mcp_servers_raw: object = loaded.get("mcp_servers")
        if not isinstance(mcp_servers_raw, dict):
            return False
        mcp_servers = cast(dict[str, object], mcp_servers_raw)
        return isinstance(mcp_servers.get("aida"), dict)
    except Exception:
        return False
