#!/usr/bin/env bash

##############################################################################
# Bash Wrapper for TypeScript Orchestrator
# Provides backward compatibility with bash-based orchestration
# Routes all calls to TypeScript implementation
#
# Usage:
#   ./orchestrate-ts.sh --task-id <id> \
#                       --mode <mvp|standard|enterprise> \
#                       --max-iterations <n>
##############################################################################

set -euo pipefail

# Determine script directory and project root
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"
ORCHESTRATION_SKILL="$SCRIPT_DIR/.."

# Input validation
sanitize_input() {
  local input="$1"
  local max_length="${2:-256}"

  input="${input:0:$max_length}"
  echo "$input" | sed 's/[^a-zA-Z0-9._:, /-]//g'
}

# Configuration
TASK_ID=""
MODE="standard"
MAX_ITERATIONS=10

# Parse arguments
while [[ $# -gt 0 ]]; do
  case $1 in
    --task-id)
      if [[ $# -lt 2 ]]; then
        echo "Error: --task-id requires a value" >&2
        exit 1
      fi
      TASK_ID=$(sanitize_input "$2") || { echo "Invalid task ID"; exit 1; }
      shift 2
      ;;
    --mode)
      if [[ $# -lt 2 ]]; then
        echo "Error: --mode requires a value" >&2
        exit 1
      fi
      MODE="$2"
      if [[ ! "$MODE" =~ ^(mvp|standard|enterprise)$ ]]; then
        echo "Invalid mode. Must be mvp, standard, or enterprise." >&2
        exit 1
      fi
      shift 2
      ;;
    --max-iterations)
      if [[ $# -lt 2 ]]; then
        echo "Error: --max-iterations requires a value" >&2
        exit 1
      fi
      if [[ ! "$2" =~ ^[1-9][0-9]*$ ]]; then
        echo "Max iterations must be a positive integer" >&2
        exit 1
      fi
      if [[ "$2" -gt 100 ]]; then
        echo "Max iterations cannot exceed 100" >&2
        exit 1
      fi
      MAX_ITERATIONS="$2"
      shift 2
      ;;
    *)
      echo "Error: Unknown option: '$1'" >&2
      echo "Usage: $0 --task-id <id> --mode <mode> --max-iterations <n>" >&2
      exit 1
      ;;
  esac
done

# Validate required arguments
if [ -z "$TASK_ID" ]; then
  echo "Error: --task-id is required" >&2
  exit 1
fi

# Ensure TypeScript is compiled
if [ ! -d "$ORCHESTRATION_SKILL/dist" ]; then
  echo "Building TypeScript orchestrator..." >&2
  cd "$ORCHESTRATION_SKILL"
  npm run build >/dev/null 2>&1 || {
    echo "Error: Failed to build TypeScript orchestrator" >&2
    exit 1
  }
fi

# Execute TypeScript orchestrator via Node
node "$ORCHESTRATION_SKILL/dist/orchestrate.js" \
  --task-id "$TASK_ID" \
  --mode "$MODE" \
  --max-iterations "$MAX_ITERATIONS"

exit $?
