#!/usr/bin/env python3
"""Tautline CLI -- thin executable shim over ``tautline_methodology.cli``.

Resolves the framework package relative to this file (a dev checkout OR the wheel's
embedded ``_dist`` tree both carry ``src/tautline_methodology`` beside ``bin/``), puts
it on ``sys.path``, then delegates to ``main()``. Every invocation path -- launcher,
snapshot store, legacy ``minervit-methodology`` execv target, CI, and the wheel runpy --
calls through here unchanged. See docs/productization/designs/arch-cli-package-split.md.
"""

from __future__ import annotations

import sys
from pathlib import Path

# Interpreter guard. Tautline needs Python 3.12+; on older Pythons the CLI starts and then core
# verbs fail with errors that never name the version. This block must stay parseable by Python 3.9
# so the message can print. A hook command (any ``-hook`` verb or ``--hook``) and ``builder-guard``
# are exempt and behave as they always did: they must never wedge a lane (see the fail-open note
# below). The test is deliberately wide: any such token anywhere in argv skips the guard.
if sys.version_info < (3, 12) and not any(
    a == "--hook" or a == "builder-guard" or a.endswith("-hook") for a in sys.argv[1:]
):
    raise SystemExit(
        "tautline needs Python 3.12 or newer, but this is Python %d.%d.%d (%s); install Python "
        "3.12+ and run tautline with it (for example python3.12 %s) or put it first on PATH"
        % (*sys.version_info[:3], sys.executable, Path(__file__).resolve())
    )

REPO_ROOT = Path(__file__).resolve().parents[1]
SRC_ROOT = REPO_ROOT / "src"
if SRC_ROOT.is_dir():
    sys.path.insert(0, str(SRC_ROOT))

try:
    from tautline_methodology.cli import main
except ModuleNotFoundError as exc:
    # Standalone copy of bin/tautline with no src/tautline_methodology sibling: the whole
    # framework engine is absent. Preserve the arch-errors-1 hook fail-open contract -- a
    # ``-hook`` command must never wedge a lane, even here -- and give every other command a
    # guided message instead of an opaque ModuleNotFoundError traceback. (Bind the cause to a
    # module global; ``except ... as exc`` unbinds ``exc`` when the handler exits, so the nested
    # main() cannot close over it.)
    _MISSING_PACKAGE_CAUSE = exc

    def main(argv: list[str] | None = None) -> int:
        args = sys.argv[1:] if argv is None else argv
        if args and args[0].endswith("-hook"):
            print(f"hook_fail_open: {args[0]} - missing framework package", file=sys.stderr)
            return 0
        raise SystemExit(
            "this command requires the framework checkout's src/tautline_methodology "
            "package; run it from a full checkout instead of a standalone copy of bin/tautline"
        ) from _MISSING_PACKAGE_CAUSE


if __name__ == "__main__":
    raise SystemExit(main())
