#!/usr/bin/env python3
"""
Test Runner for Hyperliquid Trading Bot

Runs all test modules and provides a summary of results.
"""

import sys
import os
import importlib.util
from pathlib import Path

# Add the project root to the path
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))
sys.path.insert(0, str(project_root / 'src'))

def run_test_module(test_file_path):
    """Run a single test module and return results."""
    test_name = test_file_path.stem
    
    try:
        print(f"\n{'='*60}")
        print(f"๐Ÿงช Running {test_name}")
        print(f"{'='*60}")
        
        # Load and execute the test module
        spec = importlib.util.spec_from_file_location(test_name, test_file_path)
        module = importlib.util.module_from_spec(spec)
        
        # Execute the module
        spec.loader.exec_module(module)
        
        # Try to find and run a main test function
        if hasattr(module, 'main') and callable(module.main):
            result = module.main()
            return test_name, result if isinstance(result, bool) else True
        elif hasattr(module, f'test_{test_name.replace("test_", "")}') and callable(getattr(module, f'test_{test_name.replace("test_", "")}')):
            func_name = f'test_{test_name.replace("test_", "")}'
            result = getattr(module, func_name)()
            return test_name, result if isinstance(result, bool) else True
        else:
            # If no specific test function, assume module execution was the test
            print(f"โœ… {test_name} completed (no return value)")
            return test_name, True
            
    except Exception as e:
        print(f"โŒ {test_name} failed: {e}")
        import traceback
        traceback.print_exc()
        return test_name, False

def main():
    """Run all tests and provide summary."""
    print("๐Ÿš€ Hyperliquid Trading Bot - Test Suite")
    print("="*60)
    
    # Find all test files
    tests_dir = Path(__file__).parent
    test_files = list(tests_dir.glob("test_*.py"))
    
    if not test_files:
        print("โŒ No test files found!")
        return False
    
    print(f"๐Ÿ“‹ Found {len(test_files)} test files:")
    for test_file in test_files:
        print(f"  โ€ข {test_file.name}")
    
    # Run all tests
    results = []
    for test_file in test_files:
        test_name, success = run_test_module(test_file)
        results.append((test_name, success))
    
    # Print summary
    print(f"\n{'='*60}")
    print(f"๐Ÿ“Š TEST SUMMARY")
    print(f"{'='*60}")
    
    passed = sum(1 for _, success in results if success)
    failed = len(results) - passed
    
    print(f"โœ… Passed: {passed}")
    print(f"โŒ Failed: {failed}")
    print(f"๐Ÿ“Š Total:  {len(results)}")
    
    print(f"\n๐Ÿ“‹ Individual Results:")
    for test_name, success in results:
        status = "โœ… PASS" if success else "โŒ FAIL"
        print(f"  {status} {test_name}")
    
    if failed == 0:
        print(f"\n๐ŸŽ‰ ALL TESTS PASSED!")
        print(f"๐Ÿš€ Bot is ready for deployment!")
        return True
    else:
        print(f"\n๐Ÿ’ฅ {failed} TEST(S) FAILED!")
        print(f"๐Ÿ”ง Please fix failing tests before deployment.")
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)