"""Gemini-internal JSON config writing."""

from __future__ import annotations

import json
from pathlib import Path


def get_gemini_internal_config_path(home_dir: Path | str | None = None) -> Path:
    """Return the gemini-internal config path."""
    if home_dir is None:
        home_dir = Path.home()
    else:
        home_dir = Path(home_dir)
    # Why: gemini-internal stores MCP registrations in the shared .gemini directory.
    return home_dir / ".gemini" / "settings.internal.json"


def upsert_gemini_internal_config_data(
    current_data: dict | None,
    server_name: str,
    command: str,
    args: list[str],
) -> dict:
    """Upsert a gemini-internal stdio MCP entry in JSON data."""
    data = dict(current_data or {})
    servers = dict(data.get("mcpServers") or {})
    servers[server_name] = {
        "command": command,
        "args": args,
    }
    data["mcpServers"] = servers
    return data


def remove_gemini_internal_config_data(
    current_data: dict | None,
    server_name: str,
) -> dict[str, dict | bool | None]:
    """Remove a gemini-internal MCP entry from JSON data."""
    if not current_data:
        return {"changed": False, "next_data": None}

    data = dict(current_data)
    servers = dict(data.get("mcpServers") or {})
    if server_name not in servers:
        return {"changed": False, "next_data": data}

    del servers[server_name]
    data["mcpServers"] = servers
    return {"changed": True, "next_data": data}


def write_gemini_internal_config(
    *,
    server_name: str,
    command: str,
    args: list[str],
    config_path: Path | str | None = None,
) -> str:
    """Write gemini-internal MCP config."""
    if config_path is None:
        config_path = get_gemini_internal_config_path()
    else:
        config_path = Path(config_path)

    existing_data = json.loads(config_path.read_text("utf-8")) if config_path.exists() else None
    created = existing_data is None
    next_data = upsert_gemini_internal_config_data(existing_data, server_name, command, args)

    config_path.parent.mkdir(parents=True, exist_ok=True)
    config_path.write_text(json.dumps(next_data, indent=2), "utf-8")
    return "created" if created else "updated"


def remove_gemini_internal_config(
    *,
    server_name: str,
    config_path: Path | str | None = None,
) -> str:
    """Remove gemini-internal MCP config entry."""
    if config_path is None:
        config_path = get_gemini_internal_config_path()
    else:
        config_path = Path(config_path)

    existing_data = json.loads(config_path.read_text("utf-8")) if config_path.exists() else None
    result = remove_gemini_internal_config_data(existing_data, server_name)
    if not result["changed"]:
        return "missing"

    next_data = result["next_data"]
    if next_data is None:
        config_path.unlink(missing_ok=True)
    else:
        config_path.parent.mkdir(parents=True, exist_ok=True)
        config_path.write_text(json.dumps(next_data, indent=2), "utf-8")
    return "removed"
