"""Integration tests for deploy node using test Makefiles."""

import pytest

from fwauto.nodes.deploy import deploy_node

# Skip all tests in this file - deploy_node now uses Python SSH operations
# instead of Makefiles, requiring real hardware for integration testing
pytestmark = pytest.mark.skip(reason="Deploy node uses SSH operations, requires real hardware")


@pytest.fixture
def base_state(test_project_root):
    """建立基本測試 State。"""
    hex_path = f"{test_project_root}/OBJ/Template.hex"
    return {
        "user_prompt": "test deploy integration",
        "project_root": str(test_project_root),
        "project_initialized": True,
        "build_status": "success",
        "build_errors": [],
        "build_log": "",
        "deploy_status": "pending",
        "deploy_errors": [],
        "deploy_log": "",
        "iteration": 0,
        "max_retries": 3,
        "execution_mode": "deploy",
        "command": "deploy",
        "command_args": {},
        "mode_metadata": None,
        "command_error": None,
        "log_file_path": None,
        "log_analysis_result": None,
        "firmware_path": hex_path,
    }


def test_deploy_integration_success(base_state, test_project_root, fixtures_dir):
    """
    整合測試：Flash 成功場景。

    使用測試用 Makefile 重播真實 ST-LINK 輸出。
    """
    # 讀取測試用 Makefile 並替換為絕對路徑
    fixtures_dir / "makefiles" / "flash" / "success.mk"
    target_makefile = test_project_root / ".fwauto" / "flash" / "Makefile"

    # 生成帶絕對路徑的 Makefile
    makefile_content = f"""# Test Makefile - Flash Success Scenario (Generated)

PROJECT_ROOT ?= {test_project_root}
HEX_FILE ?= $(PROJECT_ROOT)/OBJ/Template.hex

.PHONY: flash

flash:
\t@python "{fixtures_dir}/makefiles/replay_output.py" "{fixtures_dir}/outputs/stlink_flash_success.txt"
"""
    target_makefile.write_text(makefile_content)

    # 執行節點
    result = deploy_node(base_state)

    # 驗證結果
    assert result["deploy_status"] == "success"
    assert result["deploy_errors"] == []
    assert "Flash complete" in result["deploy_log"] or "燒錄成功" in result["deploy_log"]


def test_deploy_integration_hardware_error(base_state, test_project_root, fixtures_dir):
    """
    整合測試：Flash 硬體錯誤場景。

    使用測試用 Makefile 重播 ST-LINK 硬體未連接錯誤。
    """
    # 生成帶絕對路徑的 Makefile
    target_makefile = test_project_root / ".fwauto" / "flash" / "Makefile"

    makefile_content = f"""# Test Makefile - Flash Hardware Error (Generated)

PROJECT_ROOT ?= {test_project_root}
HEX_FILE ?= $(PROJECT_ROOT)/OBJ/Template.hex

.PHONY: flash

flash:
\t@python "{fixtures_dir}/makefiles/replay_output.py" "{fixtures_dir}/outputs/stlink_flash_hardware_error.txt"
\t@exit 1
"""
    target_makefile.write_text(makefile_content)

    # 執行節點
    result = deploy_node(base_state)

    # 驗證結果
    assert result["deploy_status"] == "error"
    assert len(result["deploy_errors"]) > 0
    assert "Flash failed with exit code" in result["deploy_errors"][0]


def test_deploy_integration_hex_not_exist(base_state, test_project_root, fixtures_dir):
    """
    整合測試：Flash HEX 檔案不存在場景。

    驗證節點在 HEX 檔案不存在時的錯誤處理。
    """
    # 刪除 HEX 檔案
    hex_file = test_project_root / "OBJ" / "Template.hex"
    hex_file.unlink()

    # 生成會檢查 HEX 檔案的 Makefile
    target_makefile = test_project_root / ".fwauto" / "flash" / "Makefile"

    makefile_content = f"""# Test Makefile - Flash with File Check (Generated)

PROJECT_ROOT ?= {test_project_root}
HEX_FILE ?= $(PROJECT_ROOT)/OBJ/Template.hex

.PHONY: flash

flash:
\t@if not exist "$(HEX_FILE)" (echo HEX file not found: $(HEX_FILE) && exit /b 2)
\t@python "{fixtures_dir}/makefiles/replay_output.py" "{fixtures_dir}/outputs/stlink_flash_success.txt"
"""
    target_makefile.write_text(makefile_content)

    # 執行節點
    result = deploy_node(base_state)

    # 驗證結果 - Makefile 會失敗（找不到檔案）
    assert result["deploy_status"] == "error"
    assert "Flash failed" in result["deploy_errors"][0]
