#!/usr/bin/env bash
###############################################################################
# run.sh — Proxym NLP Example: Multi-Project with Natural Language
#
# Demonstrates managing 2 projects using ONLY NLP commands via 'proxym chat':
#   Project A: "calculator" — Python calculator module + tests
#   Project B: "greeter"    — Python greeter CLI + tests
#
# Each project gets its own sprint and 2 tickets.
# All actions are performed using natural language via proxym chat.
#
# Usage:
#   bash examples/multi-project-nlp/run.sh
#   bash examples/multi-project-nlp/run.sh --dry-run
#   bash examples/multi-project-nlp/run.sh --tool claude-code
#
# Prerequisites:
#   - proxym server running (proxym serve)
#   - LLM API key configured (for NLP processing)
###############################################################################
set -euo pipefail

# ── Configuration ────────────────────────────────────────────────────────────

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROXYM_URL="${PROXYM_URL:-${DEFAULT_PROXY_URL:-http://localhost:4000}}"
TOOL="${TOOL:-aider}"
DRY_RUN=false
WAIT_TIMEOUT=120

# Project directories
PROJECT_A_DIR="${SCRIPT_DIR}/src/calculator"
PROJECT_B_DIR="${SCRIPT_DIR}/src/greeter"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --dry-run)  DRY_RUN=true; shift ;;
    --tool)     TOOL="$2"; shift 2 ;;
    --proxy)    PROXYM_URL="$2"; shift 2 ;;
    --clean)
      echo "Cleaning generated files..."
      rm -rf "${SCRIPT_DIR}/src/calculator/"* "${SCRIPT_DIR}/src/greeter/"*
      echo "Done."
      shift
      ;;
    --help|-h)
      sed -n '2,/^###/p' "$0" | head -n -1 | sed 's/^# \?//'
      exit 0
      ;;
    *) echo "Unknown option: $1"; exit 1 ;;
  esac
done

# ── Helpers ─────────────────────────────────────────────────────────────────

GREEN='\033[0;32m'; YELLOW='\033[1;33m'; RED='\033[0;31m'
CYAN='\033[0;36m'; BOLD='\033[1m'; DIM='\033[2m'; RESET='\033[0m'

_hdr()  { echo -e "\n${BOLD}${CYAN}═══ $1 ═══${RESET}"; }
_ok()   { echo -e "  ${GREEN}✓${RESET} $1"; }
_warn() { echo -e "  ${YELLOW}⚠${RESET} $1"; }
_fail() { echo -e "  ${RED}✗${RESET} $1"; }
_info() { echo -e "  ${DIM}$1${RESET}"; }
_nlp()  { echo -e "  ${CYAN}💬 NLP:${RESET} $1"; }

# ── NLP Command Helper ──────────────────────────────────────────────────────

_nlp_chat() {
  local prompt="$1"
  local description="$2"

  _nlp "$description"
  _info "  → proxym chat \"$prompt\""

  if $DRY_RUN; then
    _info "    [dry-run] Would execute: proxym chat \"$prompt\""
    return 0
  fi

  local output
  output=$(proxym chat "$prompt" 2>&1)
  local exit_code=$?

  # Show abbreviated output
  echo "$output" | head -5 | sed 's/^/    /'

  if [[ $exit_code -ne 0 ]]; then
    _warn "Command failed or LLM unavailable"
    return 1
  fi

  return 0
}

_nlp_cli() {
  local prompt="$1"
  local description="$2"

  _nlp "$description"
  _info "  → proxym chat \"$prompt\" --cli-mode --execute"

  if $DRY_RUN; then
    _info "    [dry-run] Would execute CLI generation"
    return 0
  fi

  local output
  output=$(proxym chat "$prompt" --cli-mode --execute 2>&1)
  local exit_code=$?

  echo "$output" | head -10 | sed 's/^/    /'

  if [[ $exit_code -ne 0 ]]; then
    _warn "CLI generation failed"
    return 1
  fi

  return 0
}

# ── Banner ───────────────────────────────────────────────────────────────────

echo -e "${BOLD}${CYAN}"
echo "  ╔═══════════════════════════════════════════════════════════╗"
echo "  ║  Proxym NLP Example: Multi-Project                       ║"
echo "  ║  2 projects × 2 tickets × Natural Language Commands      ║"
echo "  ╚═══════════════════════════════════════════════════════════╝"
echo -e "${RESET}"

# ── Step 1: Prerequisites ──────────────────────────────────────────────────────

_hdr "Step 1 · Prerequisites (NLP: Check System Status)"

if $DRY_RUN; then
  _info "[dry-run] Would check server via NLP"
else
  proxym status >/dev/null 2>&1 && _ok "Proxym server running" || { _fail "Server not reachable"; exit 1; }
fi

# ── Step 2: Create Project Directories ──────────────────────────────────────

_hdr "Step 2 · Create Project Directories (Manual)"

if $DRY_RUN; then
  _info "[dry-run] Would create ${PROJECT_A_DIR}/"
  _info "[dry-run] Would create ${PROJECT_B_DIR}/"
else
  mkdir -p "${PROJECT_A_DIR}" "${PROJECT_B_DIR}"
  _ok "Created calculator: ${PROJECT_A_DIR}"
  _ok "Created greeter:    ${PROJECT_B_DIR}"
fi

# ── Step 3: Register Projects via NLP ────────────────────────────────────────

_hdr "Step 3 · Register Projects via NLP"

_nlp_chat \
  "register project calculator at ${PROJECT_A_DIR} using tool ${TOOL}" \
  "Register 'calculator' project"

_nlp_chat \
  "register project greeter at ${PROJECT_B_DIR} using tool ${TOOL}" \
  "Register 'greeter' project"

# ── Step 4: Create Sprints via NLP ───────────────────────────────────────────

_hdr "Step 4 · Create Sprints via NLP"

_nlp_chat \
  "create sprint Calculator MVP with goal to build Python calculator module with tests" \
  "Create sprint for calculator"

_nlp_chat \
  "create sprint Greeter MVP with goal to build Python greeter CLI with tests" \
  "Create sprint for greeter"

# ── Step 5: Create Tickets via NLP ─────────────────────────────────────────

_hdr "Step 5 · Create Tickets via NLP"

_nlp_chat \
  "create high priority feature ticket in calculator project to implement calculator.py with add subtract multiply divide functions with type hints and error handling" \
  "Create calculator implementation ticket"

_nlp_chat \
  "create high priority test ticket in calculator project to write pytest tests for calculator functions including edge cases" \
  "Create calculator tests ticket"

_nlp_chat \
  "create high priority feature ticket in greeter project to implement greeter.py with Greeter class having hello goodbye formal methods" \
  "Create greeter implementation ticket"

_nlp_chat \
  "create high priority test ticket in greeter project to write pytest tests for Greeter class with various inputs" \
  "Create greeter tests ticket"

# ── Step 6: Dispatch via NLP/CLI ────────────────────────────────────────────

_hdr "Step 6 · Dispatch Tickets via NLP"

_nlp_cli \
  "dispatch all tickets for calculator project using ${TOOL}" \
  "Dispatch calculator tickets"

_nlp_cli \
  "dispatch all tickets for greeter project using ${TOOL}" \
  "Dispatch greeter tickets"

# ── Step 7: Wait for completion ──────────────────────────────────────────────

_hdr "Step 7 · Wait for Jobs"

if $DRY_RUN; then
  _info "[dry-run] Would wait for jobs"
else
  _info "Waiting for jobs to complete (max ${WAIT_TIMEOUT}s)..."
  elapsed=0
  while [[ $elapsed -lt $WAIT_TIMEOUT ]]; do
    active=$(proxym q 2>&1 | grep -cE "\s(running|queued)\s*$" || true)
    [[ "$active" -eq 0 ]] && { _ok "All jobs completed"; break; }
    sleep 5
    elapsed=$((elapsed + 5))
    printf "\r  ${DIM}⏳ Waiting... (%ds/${WAIT_TIMEOUT}s)${RESET}" "$elapsed"
  done
  echo ""
fi

# ── Step 8: Verify via NLP ──────────────────────────────────────────────────

_hdr "Step 8 · Verify Results via NLP"

_nlp_chat \
  "show all tickets for calculator project" \
  "List calculator tickets"

_nlp_chat \
  "show all tickets for greeter project" \
  "List greeter tickets"

_nlp_chat \
  "show sprint list" \
  "Show sprints"

_nlp_chat \
  "show kanban board" \
  "Show board"

# ── Step 9: Analyze via NLP ────────────────────────────────────────────────

_hdr "Step 9 · Analyze Tickets via NLP"

_nlp_cli \
  "analyze all completed tickets for calculator project" \
  "Analyze calculator results"

_nlp_cli \
  "analyze all completed tickets for greeter project" \
  "Analyze greeter results"

# ── Step 10: Check Generated Files ───────────────────────────────────────────

_hdr "Step 10 · Check Generated Files"

if $DRY_RUN; then
  _info "[dry-run] Would list generated files"
else
  _info "Calculator files:"
  ls -la "${PROJECT_A_DIR}"/*.py 2>/dev/null | sed 's/^/    /' || _warn "No files generated"

  echo ""
  _info "Greeter files:"
  ls -la "${PROJECT_B_DIR}"/*.py 2>/dev/null | sed 's/^/    /' || _warn "No files generated"
fi

# ── Summary ──────────────────────────────────────────────────────────────────

echo ""
echo -e "${BOLD}╔══════════════════════════════════════════════════════════════╗${RESET}"
echo -e "${BOLD}║           Multi-Project NLP Example — Complete              ║${RESET}"
echo -e "${BOLD}╠══════════════════════════════════════════════════════════════╣${RESET}"
echo -e "${BOLD}║${RESET}  Projects:  calculator, greeter"
echo -e "${BOLD}║${RESET}  Tool:      ${TOOL}"
echo -e "${BOLD}║${RESET}  Mode:      Natural Language via proxym chat"
echo -e "${BOLD}║${RESET}  Code in:   examples/multi-project-nlp/src/"
echo -e "${BOLD}║${RESET}"
echo -e "${BOLD}║${RESET}  NLP Commands Used:"
echo -e "${BOLD}║${RESET}    • Register projects"
echo -e "${BOLD}║${RESET}    • Create sprints"
echo -e "${BOLD}║${RESET}    • Create tickets"
echo -e "${BOLD}║${RESET}    • Dispatch tickets"
echo -e "${BOLD}║${RESET}    • Verify results"
echo -e "${BOLD}║${RESET}"
echo -e "${BOLD}║${RESET}  ${GREEN}✓ NLP workflow demonstrated${RESET}"
echo -e "${BOLD}╚══════════════════════════════════════════════════════════════╝${RESET}"
echo ""
_ok "Done!"
