#!/usr/bin/env bash

set -euo pipefail

trace() {
    [[ "${ZENTTY_AGENT_WRAPPER_TRACE:-}" == "1" ]] || return 0
    printf '[zentty-wrapper-trace] %s\n' "$*" >&2
}

tool_basename="${ZENTTY_AGENT_TOOL:-$(basename "$0")}"
trace "tool=${tool_basename} self=$0 args=$*"

kimi_passthrough_subcommand() {
    case "${1:-}" in
        login|logout|term|acp|info|export|mcp|plugin|vis|web)
            return 0
            ;;
        *)
            return 1
            ;;
    esac
}

kimi_early_exit_flag_present() {
    local arg
    for arg in "$@"; do
        case "$arg" in
            --help|-h|--version|-V)
                return 0
                ;;
        esac
    done
    return 1
}

should_passthrough_to_real_binary() {
    case "$tool_basename" in
        kimi|kimi-cli)
            [[ "${ZENTTY_KIMI_HOOKS_DISABLED:-}" == "1" ]] && return 0
            kimi_passthrough_subcommand "${1:-}" && return 0
            kimi_early_exit_flag_present "$@" && return 0
            return 1
            ;;
        *)
            return 1
            ;;
    esac
}

# Tools whose wrapper directory name differs from the real CLI binary name.
# cursor's CLI ships as `cursor-agent` (`cursor` itself is the IDE launcher).
# Manifest-agent wrappers export ZENTTY_AGENT_REAL_BINARIES (colon-separated).
real_binary_candidates() {
    if [[ -n "${ZENTTY_AGENT_REAL_BINARIES:-}" ]]; then
        local IFS=:
        local candidate
        for candidate in $ZENTTY_AGENT_REAL_BINARIES; do
            printf '%s\n' "$candidate"
        done
        return 0
    fi
    case "$tool_basename" in
        cursor) printf '%s\n' cursor-agent ;;
        kimi)   printf '%s\n' kimi kimi-cli ;;
        *)      printf '%s\n' "$tool_basename" ;;
    esac
}

find_real_binary() {
    local self_dir wrapper_root path_entry candidate
    self_dir="$(cd "$(dirname "$0")" && pwd)"
    wrapper_root="$(cd "${self_dir}/.." && pwd)"
    local IFS=:
    for path_entry in $PATH; do
        [[ -n "$path_entry" ]] || continue
        [[ "$path_entry" == "$self_dir" ]] && continue
        [[ "$path_entry" == "$wrapper_root" ]] && continue
        [[ "$path_entry" == "${wrapper_root}/${tool_basename}" ]] && continue
        [[ -n "${ZENTTY_AGENT_WRAPPER_DIR:-}" && "$path_entry" == "$ZENTTY_AGENT_WRAPPER_DIR" ]] && continue
        while IFS= read -r candidate; do
            [[ -x "$path_entry/$candidate" ]] || continue
            printf '%s\n' "$path_entry/$candidate"
            return 0
        done < <(real_binary_candidates)
    done
    return 1
}

zentty_cli_bin() {
    local self_dir wrapper_root bundled_cli
    self_dir="$(cd "$(dirname "$0")" && pwd)"
    wrapper_root="$(cd "${self_dir}/.." && pwd)"
    bundled_cli="${wrapper_root}/shared/zentty"
    trace "cli lookup: bundled=${bundled_cli} exists=$([[ -x "$bundled_cli" ]] && echo yes || echo no)"

    if [[ -x "$bundled_cli" ]]; then
        trace "cli resolved: bundled -> ${bundled_cli}"
        printf '%s\n' "$bundled_cli"
        return 0
    fi

    trace "cli lookup: ZENTTY_CLI_BIN=${ZENTTY_CLI_BIN:-UNSET} exists=$([[ -n "${ZENTTY_CLI_BIN:-}" && -x "${ZENTTY_CLI_BIN:-}" ]] && echo yes || echo no)"
    if [[ -n "${ZENTTY_CLI_BIN:-}" && -x "${ZENTTY_CLI_BIN}" ]]; then
        trace "cli resolved: env ZENTTY_CLI_BIN -> ${ZENTTY_CLI_BIN}"
        printf '%s\n' "$ZENTTY_CLI_BIN"
        return 0
    fi

    local path_zentty
    if path_zentty="$(command -v zentty 2>/dev/null)"; then
        trace "cli resolved: PATH -> ${path_zentty}"
        printf '%s\n' "$path_zentty"
        return 0
    fi
    trace "cli lookup: NOT FOUND (bundled missing, ZENTTY_CLI_BIN missing/unexec, no zentty on PATH)"
    return 1
}

if cli_bin="$(zentty_cli_bin 2>/dev/null)"; then
    export ZENTTY_CLI_BIN="$cli_bin"
    if should_passthrough_to_real_binary "$@"; then
        real_binary="$(find_real_binary)" || {
            echo "Error: $tool_basename not found in PATH" >&2
            exit 127
        }
        trace "passthrough: tool-specific passthrough triggered; exec real binary ${real_binary}"
        exec "$real_binary" "$@"
    fi
    trace "exec: ${cli_bin} launch ${tool_basename} $*"
    exec "$cli_bin" launch "$tool_basename" "$@"
fi

real_binary="$(find_real_binary)" || {
    echo "Error: $tool_basename not found in PATH" >&2
    exit 127
}

trace "fallback: no zentty CLI resolved; exec real binary ${real_binary} (NO STATUS WILL BE EMITTED)"
exec "$real_binary" "$@"
