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

import pytest

from fwauto.nodes.build import build_node


@pytest.fixture
def base_state(test_project_root):
    """建立基本測試 State。"""
    return {
        "user_prompt": "test build integration",
        "project_root": str(test_project_root),
        "project_initialized": True,
        "build_status": "pending",
        "build_errors": [],
        "build_log": "",
        "flash_status": "pending",
        "flash_errors": [],
        "flash_log": "",
        "iteration": 0,
        "max_retries": 3,
        "execution_mode": "build",
        "command": "build",
        "command_args": {},
        "mode_metadata": None,
        "command_error": None,
        "log_file_path": None,
        "log_analysis_result": None,
        "firmware_path": None,
    }


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

    使用測試用 Makefile 重播真實 Keil 輸出。
    """
    # 動態生成測試用 Makefile 到測試專案
    target_makefile = test_project_root / ".fwauto" / "build" / "Makefile"
    # Convert Windows paths to use forward slashes for Python -c command
    project_root_escaped = str(test_project_root).replace("\\", "/")
    makefile_content = f"""# Test Makefile - Build Success Scenario (Generated)

PROJECT_ROOT ?= {test_project_root}
PROJECT_ROOT_ESCAPED := {project_root_escaped}
MAKEFILE_DIR := $(dir $(abspath $(lastword $(MAKEFILE_LIST))))

.PHONY: build

build:
\t@python "{fixtures_dir}/makefiles/replay_output.py" "{fixtures_dir}/outputs/keil_build_success.txt"
\t@echo ""
\t@python -c "import os; \\
\t\tos.makedirs('$(PROJECT_ROOT_ESCAPED)/.fwauto', exist_ok=True); \\
\t\topen('$(PROJECT_ROOT_ESCAPED)/.fwauto/build_output.toml', 'w').write( \\
\t\t'status = \\\"success\\\"\\n\\n[output]\\nhex_file = \\\"$(PROJECT_ROOT_ESCAPED)/OBJ/Template.hex\\\"\\n')"
\t@exit 0
"""
    target_makefile.write_text(makefile_content)

    # 執行節點
    result = build_node(base_state)

    # 驗證結果
    assert result["build_status"] == "success"
    assert result["build_errors"] == []
    # 輸出中包含 "Build complete!" 或 "Build succeeded"
    assert "Build complete" in result["build_log"] or "Build succeeded" in result["build_log"]


def test_build_integration_compile_error(base_state, test_project_root, fixtures_dir):
    """
    整合測試：Build 編譯錯誤場景。

    使用測試用 Makefile 重播真實 Keil 錯誤輸出。
    """
    # 動態生成測試用 Makefile
    target_makefile = test_project_root / ".fwauto" / "build" / "Makefile"
    makefile_content = f"""# Test Makefile - Build Compile Error Scenario (Generated)

PROJECT_ROOT ?= {test_project_root}
MAKEFILE_DIR := $(dir $(abspath $(lastword $(MAKEFILE_LIST))))

.PHONY: build

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

    # 執行節點
    result = build_node(base_state)

    # 驗證結果
    assert result["build_status"] == "error"
    assert len(result["build_errors"]) > 0
    assert "Build failed with exit code" in result["build_errors"][0]
    assert result["iteration"] == 1  # 失敗應增加 iteration
    assert result["firmware_path"] is None


def test_build_integration_missing_hex(base_state, test_project_root, fixtures_dir):
    """
    整合測試：Build 成功但 HEX 檔案遺失場景。

    測試節點是否正確處理 build_output.toml 中指向不存在的檔案。
    """
    # 動態生成測試用 Makefile
    target_makefile = test_project_root / ".fwauto" / "build" / "Makefile"
    # Convert Windows paths to use forward slashes for Python -c command
    project_root_escaped = str(test_project_root).replace("\\", "/")
    makefile_content = f"""# Test Makefile - Build Missing HEX Scenario (Generated)

PROJECT_ROOT ?= {test_project_root}
PROJECT_ROOT_ESCAPED := {project_root_escaped}
MAKEFILE_DIR := $(dir $(abspath $(lastword $(MAKEFILE_LIST))))

.PHONY: build

build:
\t@python "{fixtures_dir}/makefiles/replay_output.py" "{fixtures_dir}/outputs/keil_build_success.txt"
\t@echo ""
\t@python -c "import os; \\
\t\tos.makedirs('$(PROJECT_ROOT_ESCAPED)/.fwauto', exist_ok=True); \\
\t\topen('$(PROJECT_ROOT_ESCAPED)/.fwauto/build_output.toml', 'w').write( \\
\t\t'status = \\\"success\\\"\\n\\n[output]\\nhex_file = \\\"$(PROJECT_ROOT_ESCAPED)/OBJ/NonExistent.hex\\\"\\n')"
\t@exit 0
"""
    target_makefile.write_text(makefile_content)

    # 執行節點
    result = build_node(base_state)

    # 驗證結果
    # 根據 build.py 實作，如果 build_output.toml 中的 hex_file 不存在
    # 節點會成功但 firmware_path 可能指向不存在的檔案
    # 這個測試驗證節點是否正確讀取了 toml 檔案
    assert result["build_status"] in ["success", "error"]
