"""
Author: Vasiliy Zdanovskiy
email: vasilyvz@gmail.com

Step 08 tests: SimpleConfig orchestration section and fail-fast UUID4 validation.
"""

from __future__ import annotations

import json
import uuid
from pathlib import Path

import pytest

from mcp_proxy_adapter.core.config.simple_config import SimpleConfig


def _minimal_config(**extra: object) -> dict:
    """Minimal valid config with required server section."""
    return {
        "server": {
            "host": "0.0.0.0",
            "port": 8080,
            "protocol": "http",
            "servername": "localhost",
        },
        **extra,
    }


def test_load_without_orchestration_section(tmp_path: Path) -> None:
    """When config has no orchestration key, load succeeds with default orchestration."""
    config_path = tmp_path / "config.json"
    config_path.write_text(
        json.dumps(_minimal_config(), indent=2),
        encoding="utf-8",
    )
    loader = SimpleConfig(str(config_path))
    model = loader.load()
    assert model.orchestration is not None
    assert model.orchestration.discovery_enabled is False
    assert model.orchestration.static_servers == []


def test_load_with_orchestration_empty_static_servers(tmp_path: Path) -> None:
    """Orchestration section with empty static_servers loads successfully."""
    config_path = tmp_path / "config.json"
    config_path.write_text(
        json.dumps(
            _minimal_config(
                orchestration={
                    "discovery_enabled": True,
                    "static_servers": [],
                }
            ),
            indent=2,
        ),
        encoding="utf-8",
    )
    loader = SimpleConfig(str(config_path))
    model = loader.load()
    assert model.orchestration.discovery_enabled is True
    assert model.orchestration.static_servers == []


def test_load_with_orchestration_valid_uuid4(tmp_path: Path) -> None:
    """Orchestration with static_servers with valid UUID4 loads successfully."""
    valid_id = str(uuid.uuid4())
    config_path = tmp_path / "config.json"
    config_path.write_text(
        json.dumps(
            _minimal_config(
                orchestration={
                    "discovery_enabled": True,
                    "static_servers": [
                        {"host": "localhost", "port": 9000, "id": valid_id},
                    ],
                }
            ),
            indent=2,
        ),
        encoding="utf-8",
    )
    loader = SimpleConfig(str(config_path))
    model = loader.load()
    assert len(model.orchestration.static_servers) == 1
    assert model.orchestration.static_servers[0].id == valid_id
    assert model.orchestration.static_servers[0].host == "localhost"
    assert model.orchestration.static_servers[0].port == 9000


def test_load_with_orchestration_invalid_uuid4_fails(tmp_path: Path) -> None:
    """Orchestration with static_servers with invalid UUID4 raises ValueError (fail-fast)."""
    config_path = tmp_path / "config.json"
    config_path.write_text(
        json.dumps(
            _minimal_config(
                orchestration={
                    "static_servers": [
                        {"host": "localhost", "port": 9000, "id": "not-a-uuid"},
                    ],
                }
            ),
            indent=2,
        ),
        encoding="utf-8",
    )
    loader = SimpleConfig(str(config_path))
    with pytest.raises(ValueError) as exc_info:
        loader.load()
    assert "static_servers validation failed" in str(exc_info.value)
    assert "invalid UUID4" in str(exc_info.value) or "fail-fast" in str(exc_info.value)


def test_load_with_orchestration_empty_id_fails(tmp_path: Path) -> None:
    """Orchestration with static_servers entry with empty id raises ValueError."""
    config_path = tmp_path / "config.json"
    config_path.write_text(
        json.dumps(
            _minimal_config(
                orchestration={
                    "static_servers": [
                        {"host": "localhost", "port": 9000, "id": ""},
                    ],
                }
            ),
            indent=2,
        ),
        encoding="utf-8",
    )
    loader = SimpleConfig(str(config_path))
    with pytest.raises(ValueError) as exc_info:
        loader.load()
    assert "validation failed" in str(exc_info.value)


def test_to_dict_includes_orchestration(tmp_path: Path) -> None:
    """to_dict() includes orchestration section for round-trip."""
    valid_id = str(uuid.uuid4())
    config_path = tmp_path / "config.json"
    config_path.write_text(
        json.dumps(
            _minimal_config(
                orchestration={
                    "discovery_enabled": False,
                    "static_servers": [
                        {"host": "host1", "port": 8000, "id": valid_id},
                    ],
                }
            ),
            indent=2,
        ),
        encoding="utf-8",
    )
    loader = SimpleConfig(str(config_path))
    loader.load()
    data = loader.to_dict()
    assert "orchestration" in data
    assert data["orchestration"]["discovery_enabled"] is False
    assert len(data["orchestration"]["static_servers"]) == 1
    assert data["orchestration"]["static_servers"][0]["id"] == valid_id
