#!/usr/bin/env bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
cd "$SCRIPT_DIR"

echo "================================"
echo "MindExec Local Bridge"
echo "================================"
echo

if ! command -v node >/dev/null 2>&1; then
    echo "Node.js is required. Install Node.js 20+ and try again."
    exit 1
fi

if ! command -v npm >/dev/null 2>&1; then
    echo "npm is required. Install Node.js/npm and try again."
    exit 1
fi

normalize_dir_path() {
    local target="${1:-}"
    if [[ -n "$target" && -d "$target" ]]; then
        (cd "$target" && pwd -P)
    else
        printf '%s' "$target"
    fi
}

WORKSPACE_PATH="${WORKSPACE_PATH:-$(cd "$SCRIPT_DIR/.." && pwd -P)}"
WORKSPACE_PATH="$(normalize_dir_path "$WORKSPACE_PATH")"
BRIDGE_PORT="${BRIDGE_PORT:-5167}"
RUNTIME_MARKER_FILE=".bridge-runtime"
CURRENT_RUNTIME="$(node -p "process.platform + '-' + process.arch")"

ensure_dependencies() {
    local needs_install="false"
    local reason=""

    if [[ ! -d "node_modules" ]]; then
        needs_install="true"
        reason="node_modules not found"
    elif [[ ! -f "$RUNTIME_MARKER_FILE" ]]; then
        needs_install="true"
        reason="runtime marker missing"
    else
        local recorded_runtime
        recorded_runtime="$(tr -d '\r\n' < "$RUNTIME_MARKER_FILE" 2>/dev/null || true)"
        if [[ "$recorded_runtime" != "$CURRENT_RUNTIME" ]]; then
            needs_install="true"
            reason="runtime changed (${recorded_runtime:-unknown} -> $CURRENT_RUNTIME)"
        fi
    fi

    if [[ "$needs_install" != "true" ]]; then
        return
    fi

    echo "Installing bridge dependencies..."
    if [[ -n "$reason" ]]; then
        echo "Reason: $reason"
    fi

    rm -rf node_modules
    npm install
    printf '%s\n' "$CURRENT_RUNTIME" > "$RUNTIME_MARKER_FILE"
    echo
}

ensure_dependencies

echo "Starting bridge server..."
echo "Workspace: $WORKSPACE_PATH"
echo "Port: $BRIDGE_PORT"
echo

export WORKSPACE_PATH
export BRIDGE_PORT

node launch-bridge.cjs
