"""
Test configuration management
"""

import os
import shutil
from pathlib import Path

import pytest

from mcesptool.config import ESPToolServerConfig


def test_config_from_environment():
    """Test configuration creation from environment variables"""
    config = ESPToolServerConfig.from_environment()

    assert config.esptool_path == "esptool"  # default value
    assert config.default_baud_rate == 460800
    assert config.connection_timeout == 30
    assert config.enable_stub_flasher is True
    assert config.production_mode is False


def test_config_environment_override():
    """Test environment variable override"""
    from unittest.mock import patch

    # Set test environment variables
    test_env = {
        "ESPTOOL_PATH": "/custom/esptool",
        "ESP_DEFAULT_BAUD_RATE": "115200",
        "PRODUCTION_MODE": "true",
    }

    # Temporarily override environment
    original_env = {}
    for key, value in test_env.items():
        original_env[key] = os.getenv(key)
        os.environ[key] = value

    try:
        # Mock tool availability check to always return True
        with patch.object(ESPToolServerConfig, "_check_tool_availability", return_value=True):
            config = ESPToolServerConfig.from_environment()
            assert config.esptool_path == "/custom/esptool"
            assert config.default_baud_rate == 115200
            assert config.production_mode is True
    finally:
        # Restore original environment
        for key, value in original_env.items():
            if value is None:
                os.environ.pop(key, None)
            else:
                os.environ[key] = value


def test_config_to_dict():
    """Test configuration serialization"""
    config = ESPToolServerConfig()
    config_dict = config.to_dict()

    assert isinstance(config_dict, dict)
    assert "esptool_path" in config_dict
    assert "default_baud_rate" in config_dict
    assert "production_mode" in config_dict


def test_common_ports():
    """Test common port detection"""
    config = ESPToolServerConfig()
    ports = config.get_common_ports()

    assert isinstance(ports, list)
    assert len(ports) > 0  # Should return some ports for any platform


@pytest.mark.skipif(not shutil.which("esptool"), reason="esptool not found in PATH")
def test_tool_availability():
    """Test tool availability check"""
    config = ESPToolServerConfig()

    available = config._check_tool_availability("esptool")
    assert available is True
