from __future__ import annotations

import os
import re
from pathlib import Path


def _project_root() -> Path:
    return Path(__file__).resolve().parents[2]


def _config_path(home: Path | None = None) -> Path:
    target_home = home or Path.home()
    return target_home / ".codex" / "config.toml"


def _server_block(project_root: Path) -> str:
    src_path = project_root / "src"
    return "\n".join(
        [
            "[mcp_servers.chad-ui-playwright]",
            'command = "python3"',
            'args = ["-m", "chad.mcp_playwright"]',
            f'cwd = "{project_root}"',
            f'env = {{ PYTHONPATH = "{src_path}" }}',
            "",
        ]
    )


def ensure_global_mcp_config(home: Path | None = None, project_root: Path | None = None) -> dict[str, object]:
    """Ensure Codex sees the Chad MCP server globally, regardless of CWD.

    Writes ~/.codex/config.toml (or the provided home) with the chad-ui-playwright
    server entry if missing, and updates the block if paths changed.
    """
    if os.environ.get("CHAD_SKIP_MCP_CONFIG") == "1":
        return {"changed": False, "skipped": True, "reason": "CHAD_SKIP_MCP_CONFIG=1"}

    root = project_root or _project_root()
    config_path = _config_path(home)
    block = _server_block(root)

    config_path.parent.mkdir(parents=True, exist_ok=True)
    if config_path.exists():
        text = config_path.read_text()
        if block in text:
            return {"changed": False, "path": str(config_path), "reason": "present"}

        if "[mcp_servers.chad-ui-playwright]" in text:
            new_text = re.sub(
                r"\[mcp_servers\.chad-ui-playwright\][^\[]*",
                block,
                text,
                count=1,
                flags=re.DOTALL,
            )
        else:
            new_text = f"{text.rstrip()}\n\n{block}"
        if new_text != text:
            config_path.write_text(new_text)
            return {"changed": True, "path": str(config_path), "reason": "updated"}
        return {"changed": False, "path": str(config_path), "reason": "unchanged_after_attempt"}

    config_path.write_text(f"# Auto-generated by Chad to register MCP server\n{block}")
    return {"changed": True, "path": str(config_path), "reason": "created"}


def install_cli() -> None:
    result = ensure_global_mcp_config()
    msg = "✅ Codex MCP config ensured" if result.get("changed", False) else "ℹ️ Codex MCP config already present"
    print(
        f"{msg} ({result.get('reason')}) at {result.get('path', _config_path())}",
        flush=True,
    )


if __name__ == "__main__":
    install_cli()
