"""Pytest fixtures for integration tests."""

import shutil
from pathlib import Path

import pytest


@pytest.fixture(scope="session")
def stm32_project_template() -> Path:
    """
    STM32 實例1（跑馬燈）專案模板路徑（只讀）。

    Scope: session（整個測試會話共用，避免重複驗證）
    """
    template_path = Path(r"C:\STM32F407\examples\實例1 跑馬燈實例")

    # 驗證模板存在
    if not template_path.exists():
        pytest.skip(f"STM32 project template not found: {template_path}")

    # 驗證關鍵檔案
    required_files = [
        template_path / "USER" / "main.c",
        template_path / "USER" / "stm32f4xx_it.c",
        template_path / "USER" / "LED.uvprojx",
        template_path / "HARDWARE" / "LED" / "led.c",
    ]
    for file in required_files:
        if not file.exists():
            pytest.skip(f"Required file not found: {file}")

    return template_path


@pytest.fixture
def isolated_stm32_project(tmp_path, stm32_project_template):
    """
    隔離的 STM32 專案環境（每次測試獨立副本）。

    - 複製完整專案到臨時目錄
    - 建立 .fwauto/ 結構
    - 測試完成後自動清理（pytest 自動處理）

    Returns:
        Path: 隔離專案的根目錄
    """
    # 複製專案到臨時目錄
    project_root = tmp_path / "stm32_test_project"
    shutil.copytree(stm32_project_template, project_root, symlinks=False)

    # 建立 .fwauto/ 結構（如果不存在）
    fwauto_dir = project_root / ".fwauto"
    fwauto_dir.mkdir(exist_ok=True)
    (fwauto_dir / "build").mkdir(exist_ok=True)
    (fwauto_dir / "flash").mkdir(exist_ok=True)
    (fwauto_dir / "logs").mkdir(exist_ok=True)

    # 建立 config.toml（使用 Keil 編譯器）
    config_toml = fwauto_dir / "config.toml"
    config_toml.write_text(
        """[build]
tool = "keil"
uvprojx_path = "USER/LED.uvprojx"
keil_path = "C:\\Keil_v5\\UV4\\uv4.exe"

[flash]
tool = "stlink"
"""
    )

    return project_root


@pytest.fixture
def test_project_root(tmp_path):
    """
    建立測試用專案目錄結構。

    結構：
    tmp_path/
    ├── .fwauto/
    │   ├── build/
    │   │   └── Makefile (指向測試用 Makefile)
    │   └── flash/
    │       └── Makefile (指向測試用 Makefile)
    ├── config.toml
    └── OBJ/
        └── Template.hex (空檔案)
    """
    # 建立目錄結構
    project_root = tmp_path / "test_project"
    project_root.mkdir()

    fwauto_dir = project_root / ".fwauto"
    fwauto_dir.mkdir()

    build_dir = fwauto_dir / "build"
    build_dir.mkdir()

    flash_dir = fwauto_dir / "flash"
    flash_dir.mkdir()

    obj_dir = project_root / "OBJ"
    obj_dir.mkdir()

    # 建立空的 HEX 檔案
    hex_file = obj_dir / "Template.hex"
    hex_file.write_text("dummy hex content")

    # 建立 config.toml
    config_content = """
[build]
makefile = ".fwauto/build/Makefile"
target = "build"

[flash]
makefile = ".fwauto/flash/Makefile"
target = "flash"
hex_arg = "HEX_FILE"
"""
    config_file = fwauto_dir / "config.toml"
    config_file.write_text(config_content)

    return project_root


@pytest.fixture
def fixtures_dir():
    """返回 fixtures 目錄路徑。"""
    return Path(__file__).parent.parent / "fixtures"
