#!/bin/sh
# Arize tracing hook dispatcher.
# Called by every Claude Code hook. Bootstraps the venv on first run,
# then dispatches to the named entry point.
#
# Usage: run-hook <entry-point-name>
#   e.g. run-hook arize-hook-session-start
#
# Requires CLAUDE_PLUGIN_ROOT and CLAUDE_PLUGIN_DATA env vars
# (set automatically by Claude Code for plugin hooks).
set -e

HOOK_NAME="${1:?usage: run-hook <entry-point-name>}"
PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:?CLAUDE_PLUGIN_ROOT not set}"
DATA_DIR="${CLAUDE_PLUGIN_DATA:?CLAUDE_PLUGIN_DATA not set}"
VENV_DIR="$DATA_DIR/venv"
MARKER="$DATA_DIR/.bootstrap.sha256"
BOOTSTRAP_SCRIPT="$PLUGIN_ROOT/scripts/run-hook"

# --- Find the entry point binary ---
find_entry_point() {
    if [ -x "$VENV_DIR/bin/$HOOK_NAME" ]; then
        echo "$VENV_DIR/bin/$HOOK_NAME"
    elif [ -x "$VENV_DIR/Scripts/$HOOK_NAME" ]; then
        echo "$VENV_DIR/Scripts/$HOOK_NAME"
    elif [ -x "$VENV_DIR/Scripts/${HOOK_NAME}.exe" ]; then
        echo "$VENV_DIR/Scripts/${HOOK_NAME}.exe"
    else
        return 1
    fi
}

# --- Find Python 3.11+ ---
find_python() {
    for p in python3 python py; do
        if "$p" -c "import sys; sys.exit(0 if sys.version_info>=(3,11) else 1)" 2>/dev/null; then
            echo "$p"
            return 0
        fi
    done
    return 1
}

# --- Check if (re)install is needed ---
needs_install() {
    [ ! -d "$VENV_DIR" ] && return 0
    [ ! -f "$MARKER" ] && return 0
    # Compare the package manifest and dispatcher implementation fingerprint.
    current=$("$PYTHON_CMD" -c "import hashlib,sys; print(hashlib.sha256(b''.join(open(path,'rb').read() for path in sys.argv[1:])).hexdigest())" "$PLUGIN_ROOT/pyproject.toml" "$BOOTSTRAP_SCRIPT" 2>/dev/null) || return 0
    stored=$(cat "$MARKER" 2>/dev/null) || return 0
    [ "$current" != "$stored" ]
}

# --- Bootstrap venv ---
bootstrap() {
    PYTHON_CMD=$(find_python) || {
        echo "[arize] No Python 3.11+ found — tracing will not be available" >&2
        return 1
    }

    if [ -x "$VENV_DIR/bin/python" ]; then EXISTING_PYTHON="$VENV_DIR/bin/python"
    elif [ -x "$VENV_DIR/Scripts/python.exe" ]; then EXISTING_PYTHON="$VENV_DIR/Scripts/python.exe"
    else EXISTING_PYTHON=""
    fi
    if [ -n "$EXISTING_PYTHON" ] && ! "$EXISTING_PYTHON" -c "import sys; assert sys.version_info >= (3, 11)" 2>/dev/null; then
        echo "[arize] Recreating tracing venv with Python 3.11+..." >&2
        rm -rf "$VENV_DIR"
    fi

    if ! needs_install; then
        return 0
    fi

    echo "[arize] Setting up tracing venv..." >&2
    mkdir -p "$DATA_DIR"

    "$PYTHON_CMD" -m venv "$VENV_DIR" 2>&1 | tail -3 >&2 || {
        echo "[arize] Failed to create venv" >&2
        return 1
    }

    # Runtime dependencies are intentionally empty.  Avoid invoking a build
    # backend here: Python 3.12 venvs do not include setuptools, and hooks must
    # bootstrap without network access.  Source launchers also pick up plugin
    # updates immediately instead of copying stale code into the venv.
    #
    # Standing invariant: nothing is pip-installed into this venv.  Each launcher
    # below runs `python -c "from hooks.handlers import ..."` with
    # PYTHONPATH=$CLAUDE_PLUGIN_ROOT, so every runtime import must resolve from
    # the plugin tree alone -- the `hooks.*` package and `core.*` (reachable via
    # the tracing/claude_code/core symlink) -- using only the standard library.
    # No code reachable from a hook may import `tracing.*` or any third-party
    # package: it would resolve on the pip-installed path but break on the
    # plugin path only, where tests do not exercise it.
    if [ -x "$VENV_DIR/bin/python" ]; then VENV_PYTHON="$VENV_DIR/bin/python"
    elif [ -x "$VENV_DIR/Scripts/python.exe" ]; then VENV_PYTHON="$VENV_DIR/Scripts/python.exe"
    else
        echo "[arize] Python not found in venv" >&2
        return 1
    fi
    LAUNCHER_DIR=${VENV_PYTHON%/*}

    for spec in \
        session-start:session_start session-end:session_end stop:stop \
        stop-failure:stop_failure subagent-start:subagent_start \
        subagent-stop:subagent_stop notification:notification \
        permission-request:permission_request pre-tool-use:pre_tool_use \
        post-tool-use:post_tool_use post-tool-use-failure:post_tool_use_failure \
        user-prompt-submit:user_prompt_submit user-prompt-expansion:user_prompt_expansion \
        pre-compact:pre_compact post-compact:post_compact \
        permission-denied:permission_denied; do
        suffix=${spec%%:*}
        function_name=${spec#*:}
        launcher="$LAUNCHER_DIR/arize-hook-$suffix"
        printf '%s\n' '#!/bin/sh' \
            "PYTHONPATH=\"\$CLAUDE_PLUGIN_ROOT\${PYTHONPATH:+:\$PYTHONPATH}\" exec \"$VENV_PYTHON\" -c 'from hooks.handlers import $function_name; $function_name()'" \
            > "$launcher"
        chmod +x "$launcher"
    done

    # Save bootstrap fingerprint.
    "$PYTHON_CMD" -c "import hashlib,sys; print(hashlib.sha256(b''.join(open(path,'rb').read() for path in sys.argv[1:])).hexdigest())" \
        "$PLUGIN_ROOT/pyproject.toml" "$BOOTSTRAP_SCRIPT" > "$MARKER"

    echo "[arize] Tracing venv ready" >&2
}

# --- Main ---
# Bootstrap if needed (only does work on first run or after update)
bootstrap || exit 0

# Find and exec the entry point
EP=$(find_entry_point) || {
    echo "[arize] Entry point '$HOOK_NAME' not found in venv" >&2
    exit 0
}

exec "$EP"
