from __future__ import annotations

import json

import pytest

import oh_my_linear.cli as cli


def test_main_without_args_runs_server(monkeypatch: pytest.MonkeyPatch) -> None:
    called = {"value": False}

    def _fake_serve() -> None:
        called["value"] = True

    monkeypatch.setattr(cli, "serve_main", _fake_serve)
    cli.main([])

    assert called["value"] is True


def test_install_writes_mcp_entry(tmp_path, capsys: pytest.CaptureFixture[str]) -> None:
    cli.main(
        [
            "install",
            "--project",
            str(tmp_path),
            "--name",
            "oh-my-linear",
            "--client",
            "claude",
        ]
    )

    config_path = tmp_path / ".mcp.json"
    config = json.loads(config_path.read_text(encoding="utf-8"))

    assert config["mcpServers"]["oh-my-linear"] == {
        "type": "stdio",
        "command": "uvx",
        "args": ["oh-my-linear"],
    }

    output = capsys.readouterr().out
    assert "claude mcp add oh-my-linear -- uvx oh-my-linear" in output
    assert "Codex:" not in output


def test_install_preserves_existing_custom_fields(tmp_path) -> None:
    config_path = tmp_path / ".mcp.json"
    config_path.write_text(
        json.dumps(
            {
                "mcpServers": {
                    "oh-my-linear": {
                        "type": "stdio",
                        "command": "old-command",
                        "args": ["old-arg"],
                        "env": {"LINEAR_FAST_REFRESH_TTL_SECONDS": "5"},
                    }
                }
            }
        ),
        encoding="utf-8",
    )

    cli.main(
        [
            "install",
            "--project",
            str(tmp_path),
            "--name",
            "oh-my-linear",
        ]
    )

    config = json.loads(config_path.read_text(encoding="utf-8"))
    assert config["mcpServers"]["oh-my-linear"]["command"] == "uvx"
    assert config["mcpServers"]["oh-my-linear"]["args"] == ["oh-my-linear"]
    assert config["mcpServers"]["oh-my-linear"]["env"] == {"LINEAR_FAST_REFRESH_TTL_SECONDS": "5"}


def test_install_invalid_json_exits_with_error(tmp_path) -> None:
    config_path = tmp_path / ".mcp.json"
    config_path.write_text("{invalid", encoding="utf-8")

    with pytest.raises(SystemExit, match="2"):
        cli.main(
            [
                "install",
                "--project",
                str(tmp_path),
            ]
        )
