import sys
import os

# Get the absolute path to the folder you want to add
# Example: Adding a folder named 'my_components' located in the current directory
folder_path = os.path.abspath(os.path.join("components", "system_tests"))
if folder_path not in sys.path:
    sys.path.append(folder_path)

from scan_serial import ESP32Runner
import time

def test_system_initialize():
    runner = ESP32Runner(mode="REAL", port="/dev/ttyUSB0") 
    runner.start()

    # Force print to terminal immediately
    print("--- serial Started ---", flush=True)

    try:
        start_time = time.time()
        # Loop for 30 seconds
        while time.time() - start_time < 30:
            # Wait up to 1 second for a line
            line = runner.get_line(timeout=1.0)
            if line:
                print(line, flush=True) # flush=True is critical
                
                if "System initialization complete - entering main loop" in line:
                    print("SUCCESS CRITERIA MET!", flush=True)
                    return 0
            
            # Check if the process died unexpectedly
            if runner.process.poll() is not None:
                print(f"Process exited with code: {runner.process.returncode}", flush=True)
                return 1
    finally:
        runner.stop()
        print("Done.", flush=True)
    return 1

# --- Main Logic ---
if __name__ == "__main__":
    exit_code = test_system_initialize()
    sys.exit(exit_code)
