import sys, os, subprocess

PROJECT_DIR = os.path.dirname(__file__)
sys.path.insert(0, PROJECT_DIR)

LOG = os.path.join(PROJECT_DIR, 'test_passenger.txt')

def log(msg):
    with open(LOG, 'a') as f:
        f.write(msg + '\n')

log(f"Python: {sys.version}")
log(f"Executable: {sys.executable}")

# Auto-install Flask + openpyxl si absents
missing = []
for mod in ['flask', 'openpyxl']:
    try:
        __import__(mod)
    except ImportError:
        missing.append(mod)

if missing:
    log(f"Installation auto de: {missing}")
    pip = [sys.executable, '-m', 'pip', 'install', '--quiet'] + missing
    r = subprocess.run(pip, capture_output=True, text=True, timeout=120)
    log(f"pip stdout: {r.stdout.strip()}")
    log(f"pip stderr: {r.stderr.strip()}")
    log(f"pip code: {r.returncode}")

    if r.returncode != 0:
        raise RuntimeError(f"Echec pip install: {r.stderr}")

    # Recharger les modules fraîchement installés
    import importlib
    for mod in missing:
        importlib.invalidate_caches()
        __import__(mod)
    log("Installation OK")

from app import app as application
log("App demarree avec succes")
