from __future__ import annotations

import json
import os
from argparse import Namespace
from pathlib import Path

import pytest

from mrp_mcp.config import Config, load_config


class TestConfig:
    def test_defaults(self):
        config = Config()
        assert config.relay_url == ""
        assert config.key_file is None
        assert config.agent_name is None
        assert config.capabilities == []
        assert config.metadata == {}
        assert config.poll_interval == 0
        assert config.auto_register is True

    def test_load_from_env(self, monkeypatch):
        monkeypatch.setenv("MRP_RELAY_URL", "https://relay.example.com")
        monkeypatch.setenv("MRP_KEY_FILE", "./test.key")
        monkeypatch.setenv("MRP_AGENT_NAME", "TestBot")
        monkeypatch.setenv("MRP_CAPABILITIES", "text:chat,text:summarize")
        monkeypatch.setenv("MRP_METADATA", '{"v": "1.0"}')
        monkeypatch.setenv("MRP_POLL_INTERVAL", "5")

        config = load_config()
        assert config.relay_url == "https://relay.example.com"
        assert config.key_file == "./test.key"
        assert config.agent_name == "TestBot"
        assert config.capabilities == ["text:chat", "text:summarize"]
        assert config.metadata == {"v": "1.0"}
        assert config.poll_interval == 5

    def test_load_from_cli_args(self, monkeypatch):
        monkeypatch.delenv("MRP_RELAY_URL", raising=False)
        args = Namespace(
            relay="https://cli-relay.com",
            key="./cli.key",
            name="CLI Bot",
            cap=["code:review"],
            poll_interval=10,
            config=None,
        )
        config = load_config(args)
        assert config.relay_url == "https://cli-relay.com"
        assert config.key_file == "./cli.key"
        assert config.agent_name == "CLI Bot"
        assert config.capabilities == ["code:review"]
        assert config.poll_interval == 10

    def test_cli_overrides_env(self, monkeypatch):
        monkeypatch.setenv("MRP_RELAY_URL", "https://env-relay.com")
        monkeypatch.setenv("MRP_AGENT_NAME", "EnvBot")

        args = Namespace(
            relay="https://cli-relay.com",
            key=None,
            name=None,
            cap=None,
            poll_interval=0,
            config=None,
        )
        config = load_config(args)
        assert config.relay_url == "https://cli-relay.com"
        assert config.agent_name == "EnvBot"  # not overridden since CLI name is None

    def test_load_from_config_file(self, tmp_path, monkeypatch):
        monkeypatch.delenv("MRP_RELAY_URL", raising=False)
        config_data = {
            "relay": "https://file-relay.com",
            "key_file": "./file.key",
            "name": "FileBot",
            "capabilities": ["text:chat"],
            "poll_interval": 3,
        }
        config_file = tmp_path / "mrp-mcp.json"
        config_file.write_text(json.dumps(config_data))

        args = Namespace(
            relay=None, key=None, name=None, cap=None,
            poll_interval=0, config=str(config_file),
        )
        config = load_config(args)
        assert config.relay_url == "https://file-relay.com"
        assert config.key_file == "./file.key"
        assert config.agent_name == "FileBot"

    def test_missing_relay_url_raises(self, monkeypatch):
        monkeypatch.delenv("MRP_RELAY_URL", raising=False)
        with pytest.raises(ValueError, match="relay URL is required"):
            load_config()

    def test_env_overrides_config_file(self, tmp_path, monkeypatch):
        config_data = {"relay": "https://file-relay.com", "name": "FileBot"}
        config_file = tmp_path / "mrp-mcp.json"
        config_file.write_text(json.dumps(config_data))

        monkeypatch.setenv("MRP_RELAY_URL", "https://env-relay.com")

        args = Namespace(
            relay=None, key=None, name=None, cap=None,
            poll_interval=0, config=str(config_file),
        )
        config = load_config(args)
        assert config.relay_url == "https://env-relay.com"
        assert config.agent_name == "FileBot"  # from config file
