import sys, os, traceback, shutil
from datetime import datetime

INTERP = "/home/bruhatag/virtualenv/int.artikle.in/3.13/bin/python"

if sys.executable != INTERP:
    os.execl(INTERP, INTERP, *sys.argv)

project_root = "/home/bruhatag/int.artikle.in"

if project_root not in sys.path:
    sys.path.insert(0, project_root)

os.chdir(project_root)

# ── Rotate logs on every Passenger restart ────────────────────────────────────
# stderr.log and passenger_error.log accumulate across restarts.
# On each restart: archive the old log (if non-empty) and start fresh.

def _rotate_log(log_path):
    """Archive non-empty log to logs/ folder and truncate the original."""
    try:
        if os.path.exists(log_path) and os.path.getsize(log_path) > 0:
            archive_dir = os.path.join(project_root, 'logs')
            os.makedirs(archive_dir, exist_ok=True)
            ts   = datetime.now().strftime('%Y%m%d_%H%M%S')
            name = os.path.basename(log_path).replace('.log', f'_{ts}.log')
            shutil.copy2(log_path, os.path.join(archive_dir, name))
            # Truncate — Passenger re-uses the same fd (O_APPEND) so this
            # cleanly resets the file; next write goes to offset 0.
            open(log_path, 'w').close()
    except Exception:
        pass  # Never crash passenger_wsgi over log rotation

_rotate_log(os.path.join(project_root, 'stderr.log'))
_rotate_log(os.path.join(project_root, 'passenger_error.log'))

# Write a restart marker so you know when each session started
try:
    with open(os.path.join(project_root, 'stderr.log'), 'a') as f:
        f.write(f'=== Passenger restarted at {datetime.now().strftime("%Y-%m-%d %H:%M:%S")} ===\n\n')
except Exception:
    pass

# ── Boot app ──────────────────────────────────────────────────────────────────
logfile = os.path.join(project_root, 'passenger_error.log')

try:
    from app import create_app
    application = create_app()

except Exception:
    with open(logfile, 'a') as f:
        f.write('\n\n===== STARTUP ERROR =====\n')
        traceback.print_exc(file=f)
    raise