"""Tests for MRP MCP server CLI entry point."""

from __future__ import annotations

import argparse
from unittest.mock import MagicMock, patch

import pytest

from mrp_mcp.__main__ import main


class TestMain:
    @patch("mrp_mcp.__main__.run_server")
    @patch("mrp_mcp.__main__.load_config")
    def test_argument_parsing(self, mock_load_config, mock_run_server, monkeypatch):
        mock_config = MagicMock()
        mock_load_config.return_value = mock_config

        monkeypatch.setattr(
            "sys.argv",
            [
                "mrp-mcp",
                "--relay", "http://localhost:9090",
                "--key", "/tmp/my.key",
                "--name", "MyBot",
                "--poll-interval", "10",
            ],
        )
        main()

        mock_load_config.assert_called_once()
        args = mock_load_config.call_args[0][0]
        assert args.relay == "http://localhost:9090"
        assert args.key == "/tmp/my.key"
        assert args.name == "MyBot"
        assert args.poll_interval == 10
        mock_run_server.assert_called_once_with(mock_config)

    @patch("mrp_mcp.__main__.run_server")
    @patch("mrp_mcp.__main__.load_config")
    def test_repeatable_cap(self, mock_load_config, mock_run_server, monkeypatch):
        mock_load_config.return_value = MagicMock()

        monkeypatch.setattr(
            "sys.argv",
            ["mrp-mcp", "--relay", "http://localhost:8080", "--cap", "text:chat", "--cap", "text:translate"],
        )
        main()

        args = mock_load_config.call_args[0][0]
        assert args.cap == ["text:chat", "text:translate"]

    @patch("mrp_mcp.__main__.load_config")
    def test_config_error_stderr(self, mock_load_config, monkeypatch, capsys):
        mock_load_config.side_effect = ValueError("Missing relay URL")

        monkeypatch.setattr("sys.argv", ["mrp-mcp"])

        with pytest.raises(SystemExit) as exc_info:
            main()

        assert exc_info.value.code == 1
        captured = capsys.readouterr()
        assert "Error: Missing relay URL" in captured.err

    @patch("mrp_mcp.__main__.run_server")
    @patch("mrp_mcp.__main__.load_config")
    def test_run_server_called(self, mock_load_config, mock_run_server, monkeypatch):
        mock_config = MagicMock()
        mock_load_config.return_value = mock_config

        monkeypatch.setattr("sys.argv", ["mrp-mcp", "--relay", "http://localhost:8080"])
        main()

        mock_run_server.assert_called_once_with(mock_config)
