"""py2app entry point — establishes package context so relative imports inside
`src/` work both when running `python -m src.app` AND when running as a bundled .app."""

import os
import sys
import traceback

# ── Audio helper subprocess mode ─────────────────────────────────────────
# The main app spawns this same binary with `--audio-helper` in argv to
# run an isolated CoreAudio capture child. Route to that path BEFORE any
# UI / MLX / rumps imports so the helper boots fast and doesn't drag in
# 200 MB of unused libraries. See src/audio_helper.py for the rationale —
# short version: it isolates Apple's recurring HAL mutex deadlocks so they
# can only wedge the helper, never the main process.
if "--audio-helper" in sys.argv:
    _root = os.path.dirname(os.path.abspath(__file__))
    if _root not in sys.path:
        sys.path.insert(0, _root)
    from src.audio_helper import run as _helper_run
    _helper_run()
    sys.exit(0)

# NOTE: a previous build added a `--check-permission` subprocess flag here
# so the parent could fork a fresh process to escape AXIsProcessTrusted's
# per-process cache. py2app's __boot__ doesn't always run cleanly when
# invoked through an args-only entrypoint — testers hit a "py2app launch
# error" dialog on some boots. Reverted to live in-process probes via
# AXUIElementCopyAttributeValue ("test by trying") in permissions_wizard.

# Install heavy-dep stubs (torch / sympy / scipy / numba) BEFORE anything
# else gets a chance to import mlx_whisper transitively. With stubs in place,
# the real packages can be excluded from py2app — saving ~560 MB in the .app
# bundle. See src/heavy_dep_stubs.py for the full rationale + which calls
# we're replacing.
_root = os.path.dirname(os.path.abspath(__file__))
if _root not in sys.path:
    sys.path.insert(0, _root)
from src.heavy_dep_stubs import install as _install_stubs
_install_stubs()

# Crash log to a known path so Finder/dock launches can be debugged
# (those don't have a usable stderr).
_log_path = os.path.expanduser("~/Library/Logs/Lirelle_launch.log")
try:
    os.makedirs(os.path.dirname(_log_path), exist_ok=True)
    # MUST open in UTF-8 — Python's default redirected stderr is ASCII, and any
    # non-ASCII character (→ ✓ кириллица) raises UnicodeEncodeError → cascades into
    # the py2app boot script → Launch error dialog → modal panel → notification
    # observer → re-raised Python exception → abort. Been there.
    _logf = open(_log_path, "a", buffering=1, encoding="utf-8")
    sys.stdout = _logf
    sys.stderr = _logf
    print("\n=== lumo_main launching ===")
    print(f"__file__ = {__file__}")
    print(f"cwd      = {os.getcwd()}")
    print(f"argv     = {sys.argv}")
    print(f"sys.path[0:5] = {sys.path[:5]}")
except Exception as e:
    pass


def _run():
    _root = os.path.dirname(os.path.abspath(__file__))
    if _root not in sys.path:
        sys.path.insert(0, _root)
    print(f"_root = {_root}")
    from src.app import main
    main()


if __name__ == "__main__":
    try:
        _run()
    except Exception:
        print("=== FATAL ===")
        traceback.print_exc()
        raise
