#!/usr/bin/env python
"""
Test runner script to check GUI-related tests after async refactor.
Run from project root: python test_runner.py
"""
import subprocess
import sys
import os
from pathlib import Path

def run_test(test_path, description):
    """Run a specific test and report results."""
    print(f"\n{'='*60}")
    print(f"Running: {description}")
    print(f"Test: {test_path}")
    print('='*60)

    result = subprocess.run(
        [sys.executable, "-m", "pytest", "-xvs", test_path],
        capture_output=True,
        text=True
    )

    if result.returncode == 0:
        print("✅ PASSED")
    else:
        print("❌ FAILED")
        print("\nOutput:")
        print(result.stdout)
        if result.stderr:
            print("\nErrors:")
            print(result.stderr)

    return result.returncode == 0

def check_imports():
    """Check if all required modules can be imported."""
    print("\n" + "="*60)
    print("Checking imports...")
    print("="*60)

    modules_to_check = [
        ("foundrymatch.desktop.gui", "GUI Module"),
        ("foundrymatch.desktop.engine_bridge", "Engine Bridge"),
        ("foundrymatch.desktop.models", "Models"),
        ("foundrymatch.core", "Core Module"),
        ("foundrymatch.core.engine", "Core Engine"),
    ]

    all_good = True
    for module_name, description in modules_to_check:
        try:
            __import__(module_name)
            print(f"✅ {description} ({module_name})")
        except ImportError as e:
            print(f"❌ {description} ({module_name}): {e}")
            all_good = False

    return all_good

def main():
    """Run all GUI-related tests."""
    # Change to project root
    project_root = Path(__file__).parent
    os.chdir(project_root)

    print(f"Running tests from: {project_root}")

    # First check imports
    imports_ok = check_imports()
    if not imports_ok:
        print("\n⚠️  Import issues detected. Tests may fail.")

    # Run specific tests
    tests = [
        ("tests/test_gui_bridge.py", "GUI Bridge Tests"),
        ("tests/test_engine.py::test_cached_score_roundtrip", "Engine Cache Test"),
        ("tests/test_engine.py::test_determine_optimal_blocking_strategy_successful_selection_dedupe", "Blocking Strategy Test"),
    ]

    passed = 0
    failed = 0

    for test_path, description in tests:
        if run_test(test_path, description):
            passed += 1
        else:
            failed += 1

    # Summary
    print("\n" + "="*60)
    print("SUMMARY")
    print("="*60)
    print(f"Total tests: {len(tests)}")
    print(f"Passed: {passed}")
    print(f"Failed: {failed}")

    if failed == 0:
        print("\n✅ All tests passed!")
    else:
        print(f"\n❌ {failed} tests failed.")

    return 0 if failed == 0 else 1

if __name__ == "__main__":
    sys.exit(main())
