"""
Passenger WSGI entry point for cPanel deployment.
Domain:   kiannash.ca
Username: nashkris
App path: /home/nashkris/public_html/kiannash.ca/BEACONAPLR/school_camera_app
"""

import sys
import os

# ── Hardcoded app directory (most reliable on cPanel) ────────
APP_DIR = '/home/nashkris/public_html/kiannash.ca/BEACONAPLR/school_camera_app'

# Fallback to relative path if the above doesn't exist
if not os.path.isdir(APP_DIR):
    APP_DIR = os.path.dirname(os.path.abspath(__file__))

# Set working directory so relative paths (data/, static/) work correctly
os.chdir(APP_DIR)

# Add app to Python path
if APP_DIR not in sys.path:
    sys.path.insert(0, APP_DIR)

# ── Create required directories ──────────────────────────────
os.makedirs(os.path.join(APP_DIR, 'logs'), exist_ok=True)
os.makedirs(os.path.join(APP_DIR, 'data'), exist_ok=True)
os.makedirs(os.path.join(APP_DIR, 'static', 'audio'), exist_ok=True)
os.makedirs(os.path.join(APP_DIR, 'tmp'), exist_ok=True)

# ── Logging to file ──────────────────────────────────────────
import logging
log_file = os.path.join(APP_DIR, 'logs', 'passenger.log')
logging.basicConfig(
    filename=log_file,
    level=logging.DEBUG,
    format='%(asctime)s %(levelname)s %(message)s'
)
logger = logging.getLogger(__name__)
logger.info(f"Passenger starting from: {APP_DIR}")
logger.info(f"Python: {sys.version}")
logger.info(f"sys.path: {sys.path}")

# ── Import app ───────────────────────────────────────────────
try:
    from app import app
    logger.info("App imported successfully")
except Exception as e:
    logger.exception(f"FATAL: Failed to import app: {e}")
    raise

# Passenger requires a variable named exactly 'application'
application = app
