import os
import subprocess
import tomllib
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
SCRIPT = ROOT / "scripts" / "configure-codex.sh"


def run_configure(codex_home: Path, *args: str) -> subprocess.CompletedProcess[str]:
    env = os.environ.copy()
    env["CODEX_HOME"] = str(codex_home)
    return subprocess.run(
        [str(SCRIPT), *args],
        cwd=ROOT,
        env=env,
        text=True,
        capture_output=True,
        check=True,
    )


def test_configure_codex_creates_network_setting(tmp_path: Path) -> None:
    codex_home = tmp_path / ".codex"

    run_configure(codex_home, "--skip-verify", "--skip-mcp")

    config = tomllib.loads((codex_home / "config.toml").read_text())
    assert config["sandbox_workspace_write"]["network_access"] is True


def test_configure_codex_preserves_existing_settings_and_is_idempotent(
    tmp_path: Path,
) -> None:
    codex_home = tmp_path / ".codex"
    codex_home.mkdir()
    config_path = codex_home / "config.toml"
    config_path.write_text(
        'model = "gpt-test"\n\n'
        "[sandbox_workspace_write]\n"
        "network_access = false\n"
        'writable_roots = ["/tmp/example"]\n'
    )

    run_configure(codex_home, "--skip-verify", "--skip-mcp")
    first = config_path.read_text()
    run_configure(codex_home, "--skip-verify", "--skip-mcp")

    assert config_path.read_text() == first
    config = tomllib.loads(first)
    assert config["model"] == "gpt-test"
    assert config["sandbox_workspace_write"] == {
        "network_access": True,
        "writable_roots": ["/tmp/example"],
    }


def test_configure_codex_dry_run_does_not_write(tmp_path: Path) -> None:
    codex_home = tmp_path / ".codex"

    result = run_configure(codex_home, "--dry-run", "--skip-mcp")

    assert "DRY-RUN" in result.stdout
    assert not (codex_home / "config.toml").exists()


def test_configure_codex_removes_dev_hub_registration_by_default(
    tmp_path: Path,
) -> None:
    codex_home = tmp_path / ".codex"
    codex_home.mkdir()
    config_path = codex_home / "config.toml"
    config_path.write_text(
        '[mcp_servers.dev-hub]\ncommand = "/tmp/dev-hub"\n'
    )

    result = run_configure(codex_home, "--skip-verify")

    assert "removed Codex MCP server dev-hub" in result.stdout
    config = tomllib.loads(config_path.read_text())
    assert "dev-hub" not in config.get("mcp_servers", {})


def test_configure_codex_mcp_is_explicit_opt_in(tmp_path: Path) -> None:
    codex_home = tmp_path / ".codex"

    run_configure(codex_home, "--skip-verify", "--with-mcp")

    config = tomllib.loads((codex_home / "config.toml").read_text())
    command = config["mcp_servers"]["dev-hub"]["command"]
    assert command.endswith("/scripts/codex-state-hub-mcp.sh")
