#!/bin/sh
# mokata plugin hook launcher (HOOK-RESOLVE) — the SELF-RESOLVING entry point for the
# PLUGIN route.
#
# Why this exists. A plugin `hooks.json` is STATIC: it ships in the marketplace checkout
# and cannot bake in the absolute console-script path that `mokata setup` writes (B1 /
# `harness_setup.resolved_console_script`). So it used to invoke a BARE `mokata-hook` — and
# on a GUI-launched Claude Code (launchd/Explorer, no shell profile, minimal PATH that omits
# the pip console-script dir) that bare name never resolves. Claude Code then drops the hook,
# and mokata's PreToolUse enforcement plane — secret-guard AND gate-guard — is silently OFF.
# A gate that silently does not run is worse than no gate (P14).
#
# `hooks.json` therefore invokes THIS shim via "${CLAUDE_PLUGIN_ROOT}", and the shim resolves
# mokata at hook time, in the hook's own environment — and, since 0.0.26 L8 (MP.S1), ALWAYS the
# plugin's OWN version (the plugin, its MCP server and its hooks never drift):
#
#   0. $MOKATA_HOOK        — an explicit override the user pinned themselves
#   1. the PINNED runtime  — the interpreter of the plugin's `uvx --from "mokata[full]==<version>"`
#      environment, recorded in ${CLAUDE_PLUGIN_DATA} by the plugin's MCP server (which runs in
#      it). Fast (no uv on the hot path: a warm uvx costs ~150 ms, an observe hook's budget is
#      50 ms) and complete (the `full` extra: semantic memory, code graph, the IDE)
#   2. a Python 3.12+ running THIS checkout's packaged module: `python3 -m mokata_emit` with the
#      checkout's `src/` on PYTHONPATH — identical code by construction; mokata's core is
#      dependency-free, so this works with NO install at all
#   3. `uvx --from "mokata[full]==<version>" mokata-hook` — a machine with uv and no Python
#   4. nothing resolved → ONE line on stderr naming the fix, and exit 1 (NEVER a silent 0)
#
# REMOVED at L8: `mokata-hook` on PATH and the console-script sibling of a resolved Python. Both
# ran whatever mokata happened to be installed — a CLI install of ANOTHER version served the
# plugin's hooks while the plugin's MCP server ran its own. The CLI route does not need this shim
# (it wires exec form with an absolute path), so nothing is lost by the plugin route running only
# itself.
#
# EXIT CODES ARE THE HOOK'S OWN. Every success path `exec`s, so the subcommand's exit code
# reaches Claude Code untouched — secret-guard's exit 2 still BLOCKS. Exit 1 here is the
# reserved MISCONFIGURATION code (`hook_cli.main`'s convention); exit 2 is reserved for a
# real security BLOCK (`hook_cli.BLOCK_EXIT`) and this shim never invents one.
#
# WHICH SHELL RUNS THIS (HOOK-SHELL-AGNOSTIC — read out of Claude Code 2.1.220, not assumed).
# A hook `command` is spawned by exactly one of three routes:
#   args present           -> spawn(command, args)                     NO shell at all
#   shell === "powershell" -> spawn(pwsh, [...flags, "-Command", cmd])
#   otherwise              -> spawn(cmd, [], {shell: gitBash | true})
# The default shell is bash: `sh -c` on macOS/Linux, Git Bash on Windows, or PowerShell when
# Git Bash is absent. **cmd.exe is NEVER a hook shell.** An earlier comment here claimed
# `hooks.json` names this file extension-less so cmd.exe would complete it to the `.cmd`
# through the Windows executable-extension search — that was FALSE, and it is why the gap
# survived an audit. No such completion ever happens on the hook path.
#
# So `hooks.json` pins `"shell": "bash"` on all four hooks. POSIX and Windows-with-Git-Bash run
# THIS file (Git Bash honours the shebang); a Windows box WITHOUT Git Bash gets Claude Code's
# own named error telling the user to install Git for Windows — LOUD, with a remedy, instead of
# falling through to PowerShell where a quoted path followed by an argument parses as a string
# literal and the gate silently never runs.
#
# `mokata-hook-launch.cmd` still ships beside this file for anyone invoking it directly, but it
# is NOT on the hook path: nothing in the harness routes a hook through cmd.exe.
#
# The `mokata setup claude` route does not need any of this — it wires EXEC form
# (`command` + `args`, see `harness_setup._hook_exec`), which no shell parses on any platform.
#
# Usage:  mokata-hook-launch <subcommand> [args...]
#
# Copyright 2026 MoStack. Licensed under the Apache License, Version 2.0.

set -u

_fail() {
    _mk_old_note 2>/dev/null || _mk_note=""
    echo "mokata: hooks are NOT firing — found neither a Python 3.12+ nor uv to run mokata ($1)${_mk_note}. Fix: install uv (https://docs.astral.sh/uv/getting-started/installation/; it fetches Python 3.12 itself) or Python 3.12+, and restart Claude Code, or run \`mokata setup claude\`." >&2
    exit 1
}

if [ $# -eq 0 ]; then
    _fail "no subcommand given"
fi

# NOTHING BELOW MAY CALL AN EXTERNAL BINARY. `dirname`, `basename` and friends live in /usr/bin
# — the very directory a stripped PATH omits — so using them here would break the shim in
# exactly the environment it exists to survive. Only shell BUILTINS (`command -v`, `cd`, `[`,
# parameter expansion) are used to resolve anything.
_dirname() {           # ${1%/*} with the no-slash and root cases handled — and `\` too
    # Git Bash on Windows runs a hook as `bash D:\a\…\hooks\mokata-hook-launch`: $0 has NO `/`,
    # so a `/`-only split answered `.` and the shim sourced ./mokata-plugin-env.sh from the cwd
    # (0.0.26 cut, hooks-execute · windows · git bash). The LATER of the two separators wins.
    _dn_s=${1%/*}; _dn_b=${1%\\*}
    if [ "$_dn_s" = "$1" ] && [ "$_dn_b" = "$1" ]; then
        _dirname_out=.
    elif [ "$_dn_s" = "$1" ]; then
        _dirname_out=$_dn_b
    elif [ "$_dn_b" = "$1" ]; then
        _dirname_out=$_dn_s
    elif [ ${#_dn_s} -ge ${#_dn_b} ]; then
        _dirname_out=$_dn_s
    else
        _dirname_out=$_dn_b
    fi
    [ -n "$_dirname_out" ] || _dirname_out=/
}

# This shim lives at <plugin>/src/mokata/hooks/ — so ../.. is the packaged source root that
# makes `mokata` importable without any install.
_dirname "$0"
_here=$_dirname_out
_src_dir=$(CDPATH= cd -- "$_here/../.." 2>/dev/null && pwd) || _src_dir=""

# The plugin-route helpers (version, pinned runtime, uvx). Builtins only, like this file.
. "$_here/mokata-plugin-env.sh"
_mk_read_version

# Does the given command run a Python at mokata's floor (3.12+)?  ("$@" lets us pass `py -3` as
# one command.) `_mk_py_ok` (mokata-plugin-env.sh) also remembers an older one for the last line.
_is_py3() {
    _mk_py_ok "$@"
}

# Put the plugin's own source tree on PYTHONPATH so `-m mokata_emit` works with no
# install. PREPENDED, and an existing PYTHONPATH is preserved.
_export_pythonpath() {
    if [ -n "$_src_dir" ]; then
        PYTHONPATH="$_src_dir${PYTHONPATH:+:$PYTHONPATH}"
        export PYTHONPATH
    fi
}

# Rung 2: a resolved interpreter runs THIS checkout's module. Always `exec`s — the hook's exit
# code is the subcommand's.
_run_with() {
    _py=$1
    shift
    _export_pythonpath
    exec "$_py" -m mokata_emit "$@"
}

# 0 — an explicit override wins.
if [ -n "${MOKATA_HOOK:-}" ] && [ -x "${MOKATA_HOOK}" ]; then
    exec "$MOKATA_HOOK" "$@"
fi

# 1 — the pinned runtime the plugin's MCP server recorded for THIS version. Its site-packages
#     hold exactly `mokata==<version>`, so no PYTHONPATH is needed.
if _mk_pinned_python; then
    exec "$_mk_py" -m mokata_emit "$@"
fi

# 2 — resolve a Python 3.12+ (mokata's floor) and run this checkout's module.
if [ -n "${MOKATA_PYTHON:-}" ] && _is_py3 "$MOKATA_PYTHON"; then
    _run_with "$MOKATA_PYTHON" "$@"
fi

for _cand in python3 python; do
    if command -v "$_cand" >/dev/null 2>&1 && _is_py3 "$_cand"; then
        _abs=$(command -v "$_cand")
        _run_with "$_abs" "$@"
    fi
done

# The Windows Python launcher (reachable from Git Bash).
if command -v py >/dev/null 2>&1 && _is_py3 py -3; then
    _export_pythonpath
    exec py -3 -m mokata_emit "$@"
fi

# Common install locations a minimal PATH (macOS GUI launch) omits. Overridable for testing.
_dirs=${MOKATA_PYTHON_DIRS-/opt/homebrew/bin:/usr/local/bin:/usr/bin:${HOME:-}/.pyenv/shims}
_oldifs=${IFS-}
IFS=:
for _dir in $_dirs; do
    [ -n "$_dir" ] || continue
    for _name in python3 python; do
        if [ -x "$_dir/$_name" ] && _is_py3 "$_dir/$_name"; then
            IFS=$_oldifs
            _run_with "$_dir/$_name" "$@"
        fi
    done
done
IFS=$_oldifs

# 3 — no Python at all, but uv: the pinned package, fetched once into uv's cache (the same
#     environment the MCP server uses, so it is one download, not two).
if [ -n "$_mk_version" ] && _mk_find_uvx; then
    # `python -m`, not the `mokata-hook` console script: uv's generated script calls `realpath`
    # and `dirname`, which a stripped PATH does not have (measured at L8).
    exec "$_mk_uvx" --python ">=3.12" --from "mokata[full]==$_mk_version" python -m mokata_emit "$@"
fi

# 4 — nothing resolved. LOUD and non-zero: a dead gate must never look like a passing one.
_fail "subcommand $1"
