#!/usr/bin/env bash
# Deploy all logic components as individual CF Workers
# Each component gets: {name}.arcrun.dev
#
# Usage: bash scripts/deploy-logic-components.sh [component_name]
#   (no arg = deploy all logic components)

set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
COMPONENTS_DIR="$REPO_ROOT/registry/components"
TEMPLATE_DIR="$REPO_ROOT/component-worker-template"
BUILD_DIR="$REPO_ROOT/.component-builds"

# Logic components only (no_network_syscall: true)
LOGIC_COMPONENTS=(
  if_control
  switch
  foreach_control
  filter
  merge
  try_catch
  wait
  set
  array_ops
  string_ops
  number_ops
  date_ops
  validate_json
  ai_transform_compile
  ai_transform_run
)

# Filter to single component if arg provided
if [ -n "$1" ]; then
  LOGIC_COMPONENTS=("$1")
fi

mkdir -p "$BUILD_DIR"

deploy_component() {
  local name="$1"
  local worker_name="arcrun-${name//_/-}"  # e.g. string_ops → arcrun-string-ops
  local route_name="${name//_/-}"           # e.g. string_ops → string-ops
  local wasm_file="$COMPONENTS_DIR/$name/${name}.wasm"
  local build_target="$BUILD_DIR/$name"

  echo ""
  echo "── $name ──────────────────────────────────"

  # 1. Compile WASM if not present
  if [ ! -f "$wasm_file" ]; then
    echo "  Compiling WASM..."
    (cd "$COMPONENTS_DIR/$name" && tinygo build -o "${name}.wasm" -target=wasi ./...)
  fi

  # 2. Create per-component build dir
  mkdir -p "$build_target/src"

  # 3. Copy template source
  cp "$TEMPLATE_DIR/src/index.ts" "$build_target/src/index.ts"
  cp "$TEMPLATE_DIR/package.json" "$build_target/package.json"
  cp "$TEMPLATE_DIR/tsconfig.json" "$build_target/tsconfig.json"

  # 4. Copy WASM into build dir as component.wasm
  cp "$wasm_file" "$build_target/component.wasm"

  # 5. Generate wrangler.toml
  cat > "$build_target/wrangler.toml" << TOML
name = "$worker_name"
main = "src/index.ts"
compatibility_date = "2025-02-19"

[vars]
COMPONENT_ID = "$name"

[[routes]]
pattern = "${route_name}.arcrun.dev/*"
zone_name = "arcrun.dev"
TOML

  # 6. Install deps (reuse node_modules if already installed)
  if [ ! -d "$build_target/node_modules" ]; then
    echo "  Installing deps..."
    (cd "$build_target" && npm install --legacy-peer-deps --silent)
  fi

  # 7. Deploy
  echo "  Deploying to $worker_name ($route_name.arcrun.dev)..."
  (cd "$build_target" && npx wrangler deploy)

  echo "  ✓ $name → https://${route_name}.arcrun.dev"
}

echo "Deploying ${#LOGIC_COMPONENTS[@]} logic component(s)..."

for name in "${LOGIC_COMPONENTS[@]}"; do
  if [ ! -d "$COMPONENTS_DIR/$name" ]; then
    echo "  ✗ $name: directory not found, skipping"
    continue
  fi
  deploy_component "$name"
done

echo ""
echo "Done."
