#!/usr/bin/env python3
"""hubkit entry point: python3 hubkit <command>.

For `hook` runs, an import failure must never exit non-zero in any session: it is logged to a
single import-errors.log in the state dir (a failure here cannot be classified as hub or not) and
the process exits 0.
"""
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
try:
    from hubcore.cli import main
except BaseException as exc:  # noqa: BLE001 - the hook contract is exit 0
    if len(sys.argv) > 1 and sys.argv[1] == "hook":
        try:
            import os
            import time

            base = os.environ.get("HUBKIT_STATE") or os.path.join(
                os.environ.get("XDG_STATE_HOME") or os.path.expanduser("~/.local/state"), "hubkit"
            )
            os.makedirs(base, exist_ok=True)
            with open(os.path.join(base, "import-errors.log"), "a", encoding="utf-8") as fh:
                msg = str(exc)
                try:
                    from hubcore.redact import redact

                    msg = redact(msg)[0]
                except BaseException:  # the redactor may be what failed to import
                    msg = "(message withheld: redaction unavailable)"
                fh.write(f"{time.time():.0f} {type(exc).__name__}: {msg[:200]}\n")
        except BaseException:
            pass
        sys.exit(0)
    raise
sys.exit(main())
