# -*- coding: utf-8 -*-
"""Visual diff between two .mcp.json configs."""
from typing import Any, Dict, List


def diff_configs(config_a: Dict[str, Any], config_b: Dict[str, Any],
                 label_a: str = "A", label_b: str = "B") -> List[str]:
    """Produce a human-readable diff between two configs.

    Returns list of diff lines with +/- prefixes.
    """
    lines = []
    servers_a = config_a.get("mcpServers", {})
    servers_b = config_b.get("mcpServers", {})

    all_names = sorted(set(servers_a.keys()) | set(servers_b.keys()))

    for name in all_names:
        in_a = name in servers_a
        in_b = name in servers_b

        if in_a and not in_b:
            lines.append(f"- [{label_a} only] {name}")
            _format_server(lines, servers_a[name], prefix="  - ")
            continue

        if in_b and not in_a:
            lines.append(f"+ [{label_b} only] {name}")
            _format_server(lines, servers_b[name], prefix="  + ")
            continue

        # Both have it — compare
        sa = servers_a[name]
        sb = servers_b[name]
        if sa == sb:
            lines.append(f"  [identical] {name}")
            continue

        lines.append(f"~ [modified] {name}")
        _diff_server(lines, sa, sb, label_a, label_b)

    return lines


def _format_server(lines: List[str], server: Dict, prefix: str = "  ") -> None:
    """Format a server config block."""
    for key, value in sorted(server.items()):
        lines.append(f"{prefix}{key}: {value}")


def _diff_server(lines: List[str], sa: Dict, sb: Dict,
                 label_a: str, label_b: str) -> None:
    """Diff individual fields of two server configs."""
    all_keys = sorted(set(sa.keys()) | set(sb.keys()))
    for key in all_keys:
        va = sa.get(key)
        vb = sb.get(key)

        if va == vb:
            continue

        if va is not None and vb is None:
            lines.append(f"  - {key}: {va}")
        elif va is None and vb is not None:
            lines.append(f"  + {key}: {vb}")
        else:
            lines.append(f"  - {key}: {va}")
            lines.append(f"  + {key}: {vb}")
