import os
import sys
from pathlib import Path

# cPanel / CloudLinux Python App entry point
BASE_DIR = Path(__file__).resolve().parent

# Ensure project folder is importable
if str(BASE_DIR) not in sys.path:
    sys.path.insert(0, str(BASE_DIR))

# Recommended production environment variables
os.environ.setdefault("FLASK_ENV", "production")
os.environ.setdefault("PYTHONUNBUFFERED", "1")

# Import Flask app
from app import app as application

# Initialize database when Passenger starts
try:
    from app import init_db
    init_db()
except Exception as exc:
    # Do not crash Passenger import without recording the issue
    log_dir = BASE_DIR / "logs"
    log_dir.mkdir(exist_ok=True)
    with open(log_dir / "startup_error.log", "a", encoding="utf-8") as f:
        f.write(str(exc) + "\n")
    raise
