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

echo "=== Ralph backend hardening loop ==="

# 1. Ensure we're at repo root
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

# 2. Ensure git repo
if ! git rev-parse --git-dir >/dev/null 2>&1; then
  echo "⚠️  Not in a git repo. Initializing..."
  git init
fi

# 3. Ensure RALPH_TASK.md exists
if [[ ! -f "RALPH_TASK.md" ]]; then
  echo "❌ RALPH_TASK.md không tồn tại. Hãy gọi lại Cursor để tạo task trước."
  exit 1
fi

# 4. Install Ralph scripts if missing
if [[ ! -f ".cursor/ralph-scripts/ralph-loop.sh" ]]; then
  echo "📦 Ralph scripts chưa có. Đang cài đặt..."
  curl -fsSL https://raw.githubusercontent.com/agrimsingh/ralph-wiggum-cursor/main/install.sh | bash
fi

# 5. Check cursor-agent
if ! command -v cursor-agent >/dev/null 2>&1; then
  echo "❌ cursor-agent CLI chưa cài."
  echo "   Cài bằng lệnh:"
  echo "   curl https://cursor.com/install -fsS | bash"
  exit 1
fi

# 6. Run Ralph loop on backend task
BRANCH_NAME="feature/ralph-backend-cleanup"
MAX_ITERS="${MAX_ITERATIONS:-200}"
MODEL_NAME="${RALPH_MODEL:-gpt-5.2-high}"

echo "🚀 Starting Ralph loop on branch: $BRANCH_NAME"
echo "   Max iterations: $MAX_ITERS"
echo "   Model: $MODEL_NAME"

./.cursor/ralph-scripts/ralph-loop.sh \
  -n "$MAX_ITERS" \
  -m "$MODEL_NAME" \
  --branch "$BRANCH_NAME" \
  --pr -y

echo "✅ Ralph loop finished or reached max iterations."
echo "   Kiểm tra diff + PR trên branch: $BRANCH_NAME"


