#!/usr/bin/env python3
"""
Python Wrapper for Simulation Mode Execution

This wrapper configures the Python environment to use the local
test environment packages and then executes GRIFO_M_PBIT.py in simulation mode.

Usage:
    python python_simulate_wrapper.py

This script can be executed with any Python 3.7+ interpreter and will
configure the environment to use the embedded test environment.
"""

import sys
import os
from pathlib import Path

def setup_environment():
    """Configure Python environment for test execution."""
    
    # Get script directory (GrifoAutomaticTestEnv)
    script_dir = Path(__file__).parent.resolve()
    
    # Define paths
    test_env = script_dir / "TestEnvironment"
    test_scripts = test_env / "scripts"
    test_lib = test_env / "env"
    test_site_packages = test_lib / "site-packages"
    
    # Verify paths exist
    if not test_scripts.exists():
        print(f"[ERROR] Test scripts directory not found: {test_scripts}")
        sys.exit(1)
    
    if not test_site_packages.exists():
        print(f"[ERROR] Test site-packages not found: {test_site_packages}")
        sys.exit(1)
    
    # Add to sys.path (in reverse order, will be prepended)
    paths_to_add = [
        str(test_site_packages),
        str(test_lib),
        str(test_scripts),
    ]
    
    print("=" * 79)
    print("GRIFO M-PBIT Test - Simulation Mode Wrapper")
    print("=" * 79)
    print()
    print(f"Python Version: {sys.version}")
    print(f"Python Executable: {sys.executable}")
    print()
    print("Configuring environment paths:")
    
    for path in reversed(paths_to_add):
        if path not in sys.path:
            sys.path.insert(0, path)
            print(f"  [+] {path}")
    
    print()
    print("Environment configured successfully")
    print()
    
    # Change working directory to scripts
    os.chdir(str(test_scripts))
    print(f"Working directory: {os.getcwd()}")
    print()
    
    return test_scripts

def verify_imports():
    """Verify critical imports are available."""
    
    print("Verifying imports...")
    
    required_modules = [
        'fpdf',
        'defusedxml',
        'PIL',
        'serial',
        'pyvisa',
    ]
    
    missing = []
    for module in required_modules:
        try:
            __import__(module)
            print(f"  [OK] {module}")
        except ImportError as e:
            print(f"  [MISSING] {module}: {e}")
            missing.append(module)
    
    if missing:
        print()
        print(f"[WARNING] {len(missing)} module(s) not found: {', '.join(missing)}")
        print("[WARNING] Test may fail if these modules are required")
    
    print()

def execute_test(test_scripts):
    """Execute GRIFO_M_PBIT.py with --simulate flag."""
    
    test_script = test_scripts / "GRIFO_M_PBIT.py"
    
    if not test_script.exists():
        print(f"[ERROR] Test script not found: {test_script}")
        sys.exit(1)
    
    # Check mock module
    mock_module = test_scripts / "GRIFO_M_PBIT_mock.py"
    if not mock_module.exists():
        print(f"[WARNING] Mock module not found: {mock_module}")
        print("[WARNING] Simulation mode may not work")
        print()
    
    print("=" * 79)
    print("Starting Test Execution")
    print("=" * 79)
    print()
    print(f"Test Script: {test_script.name}")
    print("Mode: SIMULATION (no hardware required)")
    print()
    print("Test Configuration:")
    print("  - Repetitions: 10 (configurable in script)")
    print("  - BIT Timeout: 180 seconds")
    print("  - PBIT Time: 15-25 seconds (randomized)")
    print()
    print("Simulation Features:")
    print("  - Simulated 1553 bus messages")
    print("  - Simulated serial terminal (%%E, %%F, RECYCLE)")
    print("  - Simulated power control")
    print("  - Configurable scenarios and timing")
    print()
    print("=" * 79)
    print()
    
    # Add --simulate flag to sys.argv
    sys.argv = [str(test_script), '--simulate']
    
    # Execute test script
    try:
        # Read and execute the test script
        with open(test_script, 'r', encoding='utf-8') as f:
            script_code = f.read()
        
        # Create globals for execution
        script_globals = {
            '__name__': '__main__',
            '__file__': str(test_script),
        }
        
        # Execute
        exec(compile(script_code, str(test_script), 'exec'), script_globals)
        
        print()
        print("=" * 79)
        print("[OK] Test completed successfully")
        print("=" * 79)
        
        return 0
        
    except Exception as e:
        print()
        print("=" * 79)
        print(f"[ERROR] Test failed with exception:")
        print("=" * 79)
        print()
        import traceback
        traceback.print_exc()
        print()
        return 1

def main():
    """Main entry point."""
    
    try:
        # Setup environment
        test_scripts = setup_environment()
        
        # Verify imports
        verify_imports()
        
        # Execute test
        exit_code = execute_test(test_scripts)
        
        sys.exit(exit_code)
        
    except KeyboardInterrupt:
        print()
        print()
        print("=" * 79)
        print("[INTERRUPTED] Test execution interrupted by user")
        print("=" * 79)
        sys.exit(130)
    
    except Exception as e:
        print()
        print("=" * 79)
        print(f"[ERROR] Wrapper failed: {e}")
        print("=" * 79)
        import traceback
        traceback.print_exc()
        sys.exit(1)

if __name__ == '__main__':
    main()
