from __future__ import annotations

from pathlib import Path

import pytest

from rabbitmq_mcp.config import RabbitMQConfig


def write_env(path: Path, content: str) -> None:
    path.write_text(content, encoding="utf-8")


def test_config_loads_test_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    env_path = tmp_path / ".env"
    write_env(
        env_path,
        """
export TEST_RABBITMQ_USER="user"
export TEST_RABBITMQ_PASSWORD="pass"
export TEST_RABBITMQ_HOST=localhost
export TEST_RABBITMQ_PORT=15672
""".strip(),
    )

    monkeypatch.delenv("RABBITMQ_USER", raising=False)
    monkeypatch.delenv("RABBITMQ_PASSWORD", raising=False)
    monkeypatch.delenv("RABBITMQ_HOST", raising=False)
    monkeypatch.delenv("RABBITMQ_PORT", raising=False)
    monkeypatch.delenv("TEST_RABBITMQ_USER", raising=False)
    monkeypatch.delenv("TEST_RABBITMQ_PASSWORD", raising=False)
    monkeypatch.delenv("TEST_RABBITMQ_HOST", raising=False)
    monkeypatch.delenv("TEST_RABBITMQ_PORT", raising=False)

    config = RabbitMQConfig.from_env(env_file=env_path, env="test")

    assert config.username == "user"
    assert config.password == "pass"
    assert config.host == "localhost"
    assert config.port == 15672
    assert config.allow_destructive is False


def test_config_prefers_direct_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
    env_path = tmp_path / ".env"
    write_env(
        env_path,
        """
export TEST_RABBITMQ_USER="user"
export TEST_RABBITMQ_PASSWORD="pass"
export TEST_RABBITMQ_HOST=localhost
""".strip(),
    )

    monkeypatch.setenv("RABBITMQ_USER", "override")
    monkeypatch.setenv("RABBITMQ_PASSWORD", "override-pass")
    monkeypatch.setenv("RABBITMQ_HOST", "override-host")

    config = RabbitMQConfig.from_env(env_file=env_path, env="test")

    assert config.username == "override"
    assert config.password == "override-pass"
    assert config.host == "override-host"
