"""簡單測試腳本，用於快速驗證測試框架功能"""

import sys
import time
from pathlib import Path

# Add parent directory to path
sys.path.insert(0, str(Path(__file__).parent.parent))

from fwauto.nodes.build import build_node
from fwauto.state import FirmwareState
from tests.integration.error_injector import ErrorInjector


def simple_test():
    """執行簡單的錯誤注入和編譯測試（不含 AI）"""

    print("=" * 60)
    print("Simple Test - Verify Error Injection and Build")
    print("=" * 60)

    # 使用實際的 STM32 專案
    project_root = Path(r"C:\STM32F407\examples\實例1 跑馬燈實例")

    # 建立 State
    state: FirmwareState = {
        "user_prompt": "Test",
        "project_root": str(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": None,
        "command": None,
        "command_args": {},
        "mode_metadata": None,
        "command_error": None,
        "log_file_path": None,
        "log_analysis_result": None,
        "firmware_path": None,
        "platform": "stm32_keil",
        "flash_output": "",
        "serial_port": "COM3",
        "baud_rate": 115200,
        "flash_retries": 0,
        "max_flash_retries": 3,
        "last_error": "",
    }

    # Step 1: 測試正常編譯
    print("\n1. Testing normal build...")
    start_time = time.time()
    result = build_node(state)
    build_time = time.time() - start_time

    if result["build_status"] == "success":
        print(f"   ✅ Build successful in {build_time:.1f}s")
    else:
        print(f"   ❌ Build failed: {result['build_errors']}")
        return 1

    # Step 2: 注入錯誤並測試編譯失敗
    print("\n2. Testing with injected error...")
    injector = ErrorInjector(project_root)

    try:
        # 注入函數名稱錯誤
        expected_error = injector.inject_error("function_name_typo")
        print("   Injected error: function_name_typo")
        print(f"   Expected error: {expected_error}")

        # 再次編譯（應該失敗）
        start_time = time.time()
        result = build_node(state)
        build_time = time.time() - start_time

        if result["build_status"] == "error":
            print(f"   ✅ Build failed as expected in {build_time:.1f}s")
            print(f"   Error messages: {result['build_errors'][:100]}...")
        else:
            print("   ❌ Build should have failed but succeeded")
            return 1

    finally:
        # 恢復原始檔案
        injector.restore()
        print("   ✅ Restored original file")

    # Step 3: 測試恢復後的編譯
    print("\n3. Testing build after restoration...")
    start_time = time.time()
    result = build_node(state)
    build_time = time.time() - start_time

    if result["build_status"] == "success":
        print(f"   ✅ Build successful after restoration in {build_time:.1f}s")
    else:
        print(f"   ❌ Build failed after restoration: {result['build_errors']}")
        return 1

    print("\n" + "=" * 60)
    print("✅ All simple tests passed!")
    print("=" * 60)

    return 0


if __name__ == "__main__":
    exit(simple_test())
