#!/usr/bin/env bash
# algochains — Safety wrapper for AlgoChains CLI bundle
# Respects MCP 2025-06-18 ToolAnnotations for safety gating
set -euo pipefail

CLI="node $(dirname "$0")/../dist/algochains-cli.js"
CMD="${1:-}"

# Tool safety classifications (from server.py annotations)
TRADE_EXEC="place-order cancel-order close-position close-all-positions deploy-strategy submit-inst-order execute-swap execute-flash-loan execute-intent approve-intent"
WRITE_DESTRUCTIVE="close-all-positions cancel-all-orders"
SAFE_TOOLS="discover-tools get-tool-details browse-strategy-marketplace massive-search-endpoints massive-get-endpoint-docs detect-market-regime detect-arbitrage detect-regime get-platform-health get-supported-brokers get-intent-history get-shadow-results analyze-sentiment get-sec-filing get-social-sentiment list-agents get-swarm-dashboard broker-health-check check-risk-alerts get-account get-positions get-orders portfolio-summary"
COMPUTE_TOOLS="run-backtest validate-strategy optimize-strategy massive-call-api massive-query-data massive-run-pipeline dispatch-gpu-task evolve-strategies create-shadow-portfolio prefetch-context"

# Parse flags
DRY_RUN=false
SAFE_ONLY=false
CONFIRM=false
for arg in "$@"; do
  case "$arg" in
    --dry-run) DRY_RUN=true ;;
    --safe-only) SAFE_ONLY=true ;;
    --confirm) CONFIRM=true ;;
  esac
done

# Remove our wrapper flags before passing to CLI
ARGS=()
for arg in "$@"; do
  case "$arg" in
    --dry-run|--safe-only|--confirm) ;; # skip wrapper flags
    *) ARGS+=("$arg") ;;
  esac
done

if [ -z "$CMD" ]; then
  echo "algochains — AI-Native Algorithmic Trading CLI"
  echo ""
  echo "Usage: algochains <command> [options]"
  echo ""
  echo "Safety flags:"
  echo "  --dry-run     Skip TRADE_EXEC and WRITE_DESTRUCTIVE tools"
  echo "  --safe-only   Only execute READ_ONLY + SEARCH + COMPUTE tools"
  echo "  --confirm     Required for TRADE_EXEC tools (bypasses confirmation prompt)"
  echo ""
  echo "Examples:"
  echo "  algochains discover-tools --query 'portfolio positions'"
  echo "  algochains detect-market-regime"
  echo "  algochains execute-intent --intent 'Get me 10K AI exposure' --dry-run"
  echo "  algochains place-order --broker alpaca --symbol AAPL --side buy --qty 10 --confirm"
  echo ""
  $CLI --help 2>&1 | tail -n +2
  exit 0
fi

# Safety checks
is_in_list() {
  local target="$1"
  local list="$2"
  for item in $list; do
    [ "$item" = "$target" ] && return 0
  done
  return 1
}

# --safe-only: block TRADE_EXEC and WRITE_DESTRUCTIVE
if $SAFE_ONLY; then
  if is_in_list "$CMD" "$TRADE_EXEC"; then
    echo "🛑 BLOCKED by --safe-only: '$CMD' is a TRADE_EXEC tool"
    echo "   Remove --safe-only to execute trading operations"
    exit 1
  fi
  if is_in_list "$CMD" "$WRITE_DESTRUCTIVE"; then
    echo "🛑 BLOCKED by --safe-only: '$CMD' is a WRITE_DESTRUCTIVE tool"
    exit 1
  fi
fi

# --dry-run: block destructive tools
if $DRY_RUN; then
  if is_in_list "$CMD" "$TRADE_EXEC"; then
    echo "⏸️  DRY-RUN: Would execute '$CMD' with args: ${ARGS[*]:1}"
    echo "   Tool classification: TRADE_EXEC"
    echo "   Remove --dry-run to execute"
    exit 0
  fi
  if is_in_list "$CMD" "$WRITE_DESTRUCTIVE"; then
    echo "⏸️  DRY-RUN: Would execute '$CMD' with args: ${ARGS[*]:1}"
    echo "   Tool classification: WRITE_DESTRUCTIVE"
    echo "   Remove --dry-run to execute"
    exit 0
  fi
fi

# TRADE_EXEC requires --confirm (unless --dry-run already handled above)
if is_in_list "$CMD" "$TRADE_EXEC" && ! $CONFIRM; then
  echo "⚠️  '$CMD' is a TRADE_EXEC tool — requires --confirm flag"
  echo ""
  echo "   This tool can place/modify real trades. Add --confirm to proceed:"
  echo "   algochains $CMD ${ARGS[*]:1} --confirm"
  echo ""
  echo "   Or use --dry-run to preview without executing:"
  echo "   algochains $CMD ${ARGS[*]:1} --dry-run"
  exit 1
fi

# WRITE_DESTRUCTIVE: extra warning even with --confirm
if is_in_list "$CMD" "$WRITE_DESTRUCTIVE" && $CONFIRM; then
  echo "🚨 DESTRUCTIVE: '$CMD' will modify ALL positions/orders"
  read -p "   Type 'YES' to proceed: " answer
  if [ "$answer" != "YES" ]; then
    echo "   Aborted."
    exit 1
  fi
fi

# Execute
exec $CLI "${ARGS[@]}"
