#!/usr/bin/env python3
"""Entry point: put src/ on the path and hand off to the real launcher."""
import os
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parent
sys.path.insert(0, str(ROOT / "src"))

# A Windows console defaults to the legacy ANSI code page (cp1252 in most
# locales), which cannot encode any of the marks this app prints — the ✓ in
# the self-test, the 📌 on a clip mark, the ✂ on a cut. Printing one raises
# UnicodeEncodeError and takes the process with it, so on a stock machine
# `--selftest` died on its FIRST line and told you nothing. Make the streams
# UTF-8 (replacing anything the terminal truly cannot render) before a
# single line is written.
if os.name == "nt":
    try:
        import ctypes
        ctypes.windll.kernel32.SetConsoleOutputCP(65001)
    except Exception:
        pass
for _stream in (sys.stdout, sys.stderr):
    try:
        _stream.reconfigure(encoding="utf-8", errors="replace")
    except Exception:
        pass                      # None under pythonw; handled just below
os.environ.setdefault("PYTHONIOENCODING", "utf-8")   # and for any child

# Windowed launch uses pythonw.exe, which sets sys.stdout/sys.stderr to
# None — the first print() then dies with AttributeError and the app
# vanishes with no window and no message. Redirect to a log file BEFORE
# importing anything that might print.
if sys.stdout is None or sys.stderr is None:
    try:
        _log = open(ROOT / "app.log", "a", buffering=1, encoding="utf-8",
                    errors="replace")
        sys.stdout = sys.stderr = _log
        import time as _t
        _log.write(f"\n===== started {_t.strftime('%Y-%m-%d %H:%M:%S')} =====\n")
    except Exception:
        import io
        sys.stdout = sys.stderr = io.StringIO()   # never let logging kill the app

# A staged update is swapped in HERE — before the app is imported, so no
# module is loaded and no file is locked.
try:
    from clipshelf.updater import apply_pending
    apply_pending()
except Exception as _e:                     # an update must never brick startup
    print(f"[update] skipped ({_e})")

from clipshelf.launch import main  # noqa: E402

if __name__ == "__main__":
    main()
