"""Integration tests for init workflow."""

import tempfile
from pathlib import Path
from unittest.mock import patch

import pytest

from src.fwauto.cli_commands.init import run_init_wizard
from src.fwauto.config import ProjectConfig
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)
        monkeypatch.setattr(Path, "home", lambda: Path(tmpdir))
        yield Path(tmpdir)


@pytest.fixture
def temp_project():
    """Create a temporary project directory."""
    with tempfile.TemporaryDirectory() as tmpdir:
        yield Path(tmpdir)


def test_complete_init_flow(temp_home, temp_project):
    """測試完整 init 流程"""
    # Mock OS 檢測為 Windows，讓 STM32 Keil 模板可用
    with patch("src.fwauto.cli_commands.init._get_current_os", return_value="windows"):
        # 模擬使用者輸入
        # 選項 1 是 AM62x, 選項 2 是 STM32F4
        with patch("rich.prompt.IntPrompt.ask", return_value=2):  # 選擇 STM32 (第 2 個選項)
            with patch("rich.prompt.Prompt.ask") as mock_prompt:
                mock_prompt.side_effect = [
                    "/tmp",  # SDK 路徑（使用存在的路徑避免額外確認）
                    "unknown",  # SDK 版本
                    "stm32f4",  # 裝置系列
                    "STM32F407VGT6",  # 裝置型號
                ]

                success = run_init_wizard(temp_project, overwrite=False)
                assert success

    # 驗證檔案結構
    fwauto_dir = temp_project / ".fwauto"
    assert fwauto_dir.exists()
    assert (fwauto_dir / "config.toml").exists()
    assert (fwauto_dir / "build" / "Makefile").exists()
    assert (fwauto_dir / "build" / "build.ps1").exists()
    assert (fwauto_dir / "deploy" / "Makefile").exists()
    assert (fwauto_dir / "deploy" / "deploy.ps1").exists()
    assert (fwauto_dir / "logs").exists()

    # 驗證 config 內容
    config = ProjectConfig(fwauto_dir / "config.toml")
    assert config.sdk_type == "stm32f4"  # sdk_type 來自 metadata.toml 中的 sdk.id
    assert config.device_family == "stm32f4"
    assert config.device_model == "STM32F407VGT6"


def test_init_with_existing_user_config(temp_home, temp_project):
    """測試使用現有 User Config 的流程"""
    # 先建立 User Config - 使用 stm32f4 作為 sdk_type (來自 metadata.toml 的 sdk.id)
    user_config = UserConfig()
    user_config.set_sdk_config("stm32f4", {"type": "keil", "path": "/tmp", "version": "5.35"})
    user_config.set_device_config("stm32f4", {"family": "stm32f4", "model": "STM32F407VGT6"})

    # Mock OS 檢測為 Windows，讓 STM32 Keil SDK 可用
    with patch("src.fwauto.cli_commands.init._get_current_os", return_value="windows"):
        # 模擬使用者輸入（使用現有 SDK 設定）
        with patch("rich.prompt.IntPrompt.ask", return_value=1):  # 選擇第一個 (已配置的 stm32f4)
            success = run_init_wizard(temp_project, overwrite=False)
            assert success

    # 驗證 SDK 路徑從 User Config 繼承
    config = ProjectConfig(temp_project / ".fwauto" / "config.toml")
    assert config.sdk_path == "/tmp"
    assert config.sdk_type == "stm32f4"
    assert config.device_family == "stm32f4"
    assert config.device_model == "STM32F407VGT6"


def test_init_overwrite(temp_home, temp_project):
    """測試 overwrite 模式"""
    # Mock OS 檢測為 Windows
    with patch("src.fwauto.cli_commands.init._get_current_os", return_value="windows"):
        # 第一次 init - 選項 2 是 STM32F4
        with patch("rich.prompt.IntPrompt.ask", return_value=2):
            with patch("rich.prompt.Prompt.ask") as mock_prompt:
                mock_prompt.side_effect = [
                    "/tmp",
                    "unknown",
                    "stm32f4",
                    "STM32F407VGT6",
                ]
                run_init_wizard(temp_project, overwrite=False)

        # 修改 Makefile
        makefile = temp_project / ".fwauto" / "build" / "Makefile"
        original_content = makefile.read_text()
        makefile.write_text("modified content")

        # 第二次 init with overwrite - 選擇已配置的 stm32f4
        with patch("rich.prompt.IntPrompt.ask", return_value=1):
            run_init_wizard(temp_project, overwrite=True)

    # 驗證 Makefile 被恢復
    assert makefile.read_text() == original_content
