#!/bin/sh
set -e

for cmd in mcp-to-command mcp-remote; do
    command -v "$cmd" >/dev/null 2>&1 || { echo "Error: Missing required command: $cmd" >&2; exit 1; }
done

if [ -z "$OLLIE_LOGSEQ_TOKEN" ]; then
    echo "Error: OLLIE_LOGSEQ_TOKEN not set" >&2
    exit 1
fi

LOGSEQ_MCP_URL="${LOGSEQ_MCP_URL:-http://127.0.0.1:12315}"

have_timeout=
command -v timeout >/dev/null 2>&1 && have_timeout=1

if [ -n "$have_timeout" ]; then
    exec timeout 30 mcp-to-command mcp-remote "$LOGSEQ_MCP_URL/mcp" --transport http-first --header "Authorization: Bearer $OLLIE_LOGSEQ_TOKEN" -- "$@" || {
        if [ $? -eq 124 ]; then
            echo "Error: timeout exceeded, may want to retry" >&2
            exit 124
        else
            exit $?
        fi
    }
fi

exec mcp-to-command mcp-remote "$LOGSEQ_MCP_URL/mcp" --transport http-first --header "Authorization: Bearer $OLLIE_LOGSEQ_TOKEN" -- "$@"
