"""نقطة تشغيل cPanel (Passenger) — بتشغّل نفس التطبيق عبر WSGI."""

import os
import sys
import threading
import time
import traceback

BASE_DIR = os.path.dirname(os.path.abspath(__file__))
os.chdir(BASE_DIR)
if BASE_DIR not in sys.path:
    sys.path.insert(0, BASE_DIR)

BOOT_LOG = os.path.join(BASE_DIR, "wsgi_boot.log")
ERROR_LOG = os.path.join(BASE_DIR, "wsgi_error.log")
_STARTED = False

try:
    with open(BOOT_LOG, "a", encoding="utf-8") as fh:
        fh.write(f"boot {time.strftime('%Y-%m-%d %H:%M:%S')} python {sys.version}\n")
except Exception:
    pass


def _start_background():
    global _STARTED
    if _STARTED:
        return
    _STARTED = True
    dashboard.bootstrap()
    for target in (dashboard.sheet_auto_loop, dashboard.meta_auto_loop, dashboard.easy_gap_loop):
        threading.Thread(target=target, daemon=True).start()


try:
    import app as dashboard  # noqa: E402
    from wsgi_bridge import call as _call  # noqa: E402

    def application(environ, start_response):
        global _STARTED
        if not _STARTED:
            _STARTED = True
            try:
                _start_background()
            except Exception:  # noqa: BLE001
                with open(ERROR_LOG, "a", encoding="utf-8") as fh:
                    fh.write("background start failed:\n" + traceback.format_exc() + "\n")
        return _call(environ, start_response)

except Exception:  # noqa: BLE001
    IMPORT_ERROR = traceback.format_exc()
    with open(ERROR_LOG, "w", encoding="utf-8") as fh:
        fh.write(IMPORT_ERROR)

    def application(environ, start_response):
        start_response("500 Internal Server Error",
                       [("Content-Type", "text/plain; charset=utf-8")])
        return [IMPORT_ERROR.encode("utf-8", "replace")]
