"""
Tests for configuration manager.
"""

import os
import tempfile
from pathlib import Path

import pytest

from airctl.config.manager import ConfigManager
from airctl.config.defaults import get_default_config


class TestConfigManager:
    """Tests for ConfigManager class."""

    @pytest.fixture
    def temp_config_path(self):
        """Create a temporary config file path."""
        with tempfile.TemporaryDirectory() as tmpdir:
            yield os.path.join(tmpdir, "config.yaml")

    def test_load_empty_config(self, temp_config_path):
        """Test loading when no config file exists."""
        config = ConfigManager(config_path=temp_config_path)

        assert config.get("version") == 1
        assert os.path.exists(temp_config_path)

    def test_set_and_get(self, temp_config_path):
        """Test setting and getting values."""
        config = ConfigManager(config_path=temp_config_path)

        config.set("test.key", "value")
        assert config.get("test.key") == "value"

    def test_get_with_default(self, temp_config_path):
        """Test getting non-existent key with default."""
        config = ConfigManager(config_path=temp_config_path)

        assert config.get("nonexistent", "default") == "default"

    def test_alias_operations(self, temp_config_path):
        """Test alias operations."""
        config = ConfigManager(config_path=temp_config_path)

        config.set_alias("AA:BB:CC:DD:EE:FF", "my-device")

        assert config.get_address_by_alias("my-device") == "AA:BB:CC:DD:EE:FF"
        assert "my-device" in config.get("aliases", {})

        config.remove_alias("my-device")
        assert config.get_address_by_alias("my-device") is None

    def test_preset_operations(self, temp_config_path):
        """Test preset operations."""
        config = ConfigManager(config_path=temp_config_path)

        preset = config.get_preset("uart")
        assert preset is not None
        assert "service" in preset

        config.set_preset("custom", {"service": "custom-uuid"})
        assert config.get_preset("custom") == {"service": "custom-uuid"}

        config.remove_preset("custom")
        assert config.get_preset("custom") is None

    def test_reset(self, temp_config_path):
        """Test configuration reset."""
        config = ConfigManager(config_path=temp_config_path)

        config.set("test.key", "value")
        config.reset()

        assert config.get("test.key") is None
        assert config.get("version") == 1

    def test_persistence(self, temp_config_path):
        """Test configuration persistence."""
        config1 = ConfigManager(config_path=temp_config_path)
        config1.set_alias("AA:BB:CC:DD:EE:FF", "device1")

        config2 = ConfigManager(config_path=temp_config_path)
        assert config2.get_address_by_alias("device1") == "AA:BB:CC:DD:EE:FF"
