#!/usr/bin/env python
"""
GRIFO_M_PBIT Simulation Mode Launcher

This script is designed to be executed by uPlatSim.exe and will launch
GRIFO_M_PBIT.py in simulation mode by injecting the --simulate flag.

Usage (via uPlatSim.exe):
    uPlatSim.exe --ini config.ini --batch GRIFO_M_PBIT_simulate_launcher.py
"""

import sys
import os

# Get the directory of this script (use sys.argv[0] as fallback for __file__)
try:
    script_path = __file__
except NameError:
    script_path = sys.argv[0] if sys.argv else os.path.abspath(__file__)

script_dir = os.path.dirname(os.path.abspath(script_path))

# Execute the main test script
main_script = os.path.join(script_dir, 'GRIFO_M_PBIT.py')

if not os.path.exists(main_script):
    print(f"ERROR: Cannot find GRIFO_M_PBIT.py at: {main_script}")
    sys.exit(1)

# CRITICAL: Update sys.argv[0] to point to the main test script
# This is required because the test uses sys.argv[0] to locate its JSON config file
sys.argv[0] = main_script

# Add --simulate flag to sys.argv AFTER setting argv[0]
if '--simulate' not in sys.argv:
    sys.argv.append('--simulate')

print("=" * 79)
print("GRIFO M-PBIT Test - Simulation Mode Launcher")
print("=" * 79)
print()
print("This script will execute GRIFO_M_PBIT.py in SIMULATION mode")
print("No hardware connection required")
print()
print("=" * 79)
print()

# CRITICAL: Setup simulation BEFORE executing main script
# This must happen before leo_grifo_1553 and other modules are imported
print("Setting up simulation environment...")
print()

try:
    from GRIFO_M_PBIT_mock import initialize_simulation, setup_simulation
    
    # Step 1: Initialize with user interaction (ONCE)
    print("[1/2] Asking user for configuration...")
    initialize_simulation()
    
    # Step 2: Setup mock modules
    print("[2/2] Injecting mock modules...")
    setup_simulation()
    
    print("[OK] Simulation environment configured")
    print("     - Mock 1553 interface active")
    print("     - Mock power control active")
    print()
except ImportError as e:
    print(f"[ERROR] Cannot import simulation mock: {e}")
    print("[ERROR] GRIFO_M_PBIT_mock.py must be in the same directory")
    sys.exit(1)
except Exception as e:
    print(f"[ERROR] Simulation setup failed: {e}")
    import traceback
    traceback.print_exc()
    sys.exit(1)

print()
print("Executing test...")
print("=" * 79)
print()

# Read and execute the main script
with open(main_script, 'r', encoding='utf-8') as f:
    script_code = f.read()

# Create globals for execution
script_globals = {
    '__name__': '__main__',
    '__file__': main_script,
}

# Execute
try:
    exec(compile(script_code, main_script, 'exec'), script_globals)
except SystemExit as e:
    # Propagate exit code from main script
    sys.exit(e.code)
except Exception as e:
    print()
    print("=" * 79)
    print("ERROR: Test execution failed")
    print("=" * 79)
    print()
    import traceback
    traceback.print_exc()
    sys.exit(1)
