"""Tests for UserConfig."""

import tempfile
from pathlib import Path

import pytest

from src.fwauto.user_config import UserConfig


@pytest.fixture
def temp_home(monkeypatch):
    """Create a temporary home directory for testing."""
    with tempfile.TemporaryDirectory() as tmpdir:
        monkeypatch.setenv("HOME", tmpdir)
        # Monkey-patch Path.home() to return the temp directory
        monkeypatch.setattr(Path, "home", lambda: Path(tmpdir))
        yield Path(tmpdir)


def test_user_config_load_nonexistent(temp_home):
    """測試載入不存在的 config"""
    config = UserConfig()
    assert config.data == {}
    assert config.config_path == temp_home / ".fwauto" / "config.toml"


def test_user_config_set_sdk(temp_home):
    """測試設定 SDK 資訊"""
    config = UserConfig()
    config.set_sdk_config("stm32_keil", {"type": "keil", "path": "C:\\Keil_v5", "version": "5.35"})

    # 驗證資料
    assert config.get_sdk_config("stm32_keil")["path"] == "C:\\Keil_v5"
    assert config.get_sdk_config("stm32_keil")["version"] == "5.35"

    # 驗證檔案存在
    assert config.config_path.exists()


def test_user_config_get_nonexistent_sdk(temp_home):
    """測試取得不存在的 SDK"""
    config = UserConfig()
    assert config.get_sdk_config("nonexistent") is None


def test_user_config_persist(temp_home):
    """測試 config 持久化"""
    config1 = UserConfig()
    config1.set_sdk_config("stm32_keil", {"type": "keil", "path": "C:\\Keil_v5"})

    # 建立新的 UserConfig 實例，應該能讀取到之前儲存的資料
    config2 = UserConfig()
    assert config2.get_sdk_config("stm32_keil")["path"] == "C:\\Keil_v5"


def test_user_config_multiple_sdks(temp_home):
    """測試儲存多個 SDK"""
    config = UserConfig()
    config.set_sdk_config("stm32_keil", {"type": "keil", "path": "C:\\Keil_v5"})
    config.set_sdk_config("am62x", {"type": "ti", "path": "/opt/ti-sdk"})

    assert config.get_sdk_config("stm32_keil")["path"] == "C:\\Keil_v5"
    assert config.get_sdk_config("am62x")["path"] == "/opt/ti-sdk"


def test_user_config_set_deployment(temp_home):
    """測試設定 deployment 資訊"""
    config = UserConfig()
    config.set_deployment_config(
        "am62x",
        {
            "board_ip": "192.168.1.100",
            "board_user": "admin",
            "deploy_path": "/tmp/test",
            "ssh_options": "-o ConnectTimeout=10",
        },
    )

    # 驗證資料
    deployment = config.get_deployment_config("am62x")
    assert deployment["board_ip"] == "192.168.1.100"
    assert deployment["board_user"] == "admin"
    assert deployment["deploy_path"] == "/tmp/test"
    assert deployment["ssh_options"] == "-o ConnectTimeout=10"

    # 驗證檔案存在
    assert config.config_path.exists()


def test_user_config_get_nonexistent_deployment(temp_home):
    """測試取得不存在的 deployment"""
    config = UserConfig()
    assert config.get_deployment_config("nonexistent") is None
