#!/usr/bin/env bash
# ─────────────────────────────────────────────────────────────
# Parsec Sdn. Bhd. · AMIR
# Generated by the Parsec Sdn. Bhd. AI Development Framework v2
# © 2026 Parsec Sdn. Bhd.. All rights reserved.
# Internal use only. Unauthorised use outside Parsec Sdn. Bhd.-authorised
# projects is prohibited.
# ─────────────────────────────────────────────────────────────
# review.sh — Level 4 batch review
# Usage: ./review.sh [batch-name]
# Lists open PRs for the batch, shows CI status, runs pre-merge conflict simulation,
# and summarises agent logs. Run after dispatch.sh agents have finished.
#
# Bash 3 compatible — no namerefs, no associative arrays
# shellcheck shell=bash
set -euo pipefail

BATCH_NAME="${1:-}"
PRIMARY_DIR="$(pwd)"
LOG_DIR="$PRIMARY_DIR/logs"

if [ -z "$BATCH_NAME" ]; then
  echo "Usage: ./review.sh [batch-name]"
  echo "Lists open PRs, CI status, and merge conflict simulation for the batch."
  exit 1
fi

# Pull the batch entries from dispatch.sh
get_batch() {
  local name
  name="$(echo "$1" | tr '-' '_')"
  echo "$name" | grep -qE '^[a-zA-Z0-9_]+$' || return 1
  grep "^BATCH_${name}=" dispatch.sh | sed 's/^BATCH_'"${name}"'=//;s/^"//;s/"$//'
}

BATCH_ENTRIES="$(get_batch "$BATCH_NAME" 2>/dev/null || true)"
if [ -z "$BATCH_ENTRIES" ]; then
  echo "No batch '$BATCH_NAME' found in dispatch.sh. Available batches:"
  grep '^BATCH_' dispatch.sh | sed 's/BATCH_//;s/=.*//' | tr '_' '-'
  exit 1
fi

echo ""
echo "════════════════════════════════════════════════════════════"
echo " Review — Batch: $BATCH_NAME"
echo "════════════════════════════════════════════════════════════"

# ── 1. Per-task summary ──────────────────────────────────────
echo ""
echo "▶ TASKS IN BATCH"
echo ""
echo "  Task ID     Branch                              Worktree"
echo "  ─────────   ──────────────────────────────────  ──────────"

declare TASK_BRANCHES=""
declare TASK_IDS=""

for entry in $BATCH_ENTRIES; do
  TASK_ID="${entry%%:*}"
  REST="${entry#*:}"
  BRANCH="${REST%%:*}"
  WORKTREE="${REST#*:}"
  WT_NAME="$(basename "$WORKTREE")"
  printf "  %-11s %-35s %s\n" "$TASK_ID" "$BRANCH" "$WT_NAME"
  TASK_BRANCHES="$TASK_BRANCHES $BRANCH"
  TASK_IDS="$TASK_IDS $TASK_ID"
done

# ── 2. Open PRs + CI status (uses gh CLI) ────────────────────
echo ""
echo "▶ PR STATUS"
echo ""

if ! command -v gh &>/dev/null; then
  echo "  ⚠ gh CLI not installed — skipping PR status check"
  echo "    Install: brew install gh && gh auth login"
else
  for branch in $TASK_BRANCHES; do
    PR_INFO="$(gh pr list --head "$branch" --json number,title,state,statusCheckRollup --jq '.[0]' 2>/dev/null || echo '')"
    if [ -z "$PR_INFO" ] || [ "$PR_INFO" = "null" ]; then
      printf "  %-35s %s\n" "$branch" "✗ no open PR"
      continue
    fi
    PR_NUM="$(echo "$PR_INFO" | grep -o '"number":[0-9]*' | head -1 | cut -d: -f2)"
    PR_STATE="$(echo "$PR_INFO" | grep -o '"state":"[^"]*"' | head -1 | cut -d'"' -f4)"
    PR_TITLE="$(echo "$PR_INFO" | grep -o '"title":"[^"]*"' | head -1 | cut -d'"' -f4)"
    
    # CI rollup
    CI_STATE="$(echo "$PR_INFO" | grep -oE '"conclusion":"[^"]*"' | head -1 | cut -d'"' -f4)"
    [ -z "$CI_STATE" ] && CI_STATE="pending"
    
    case "$CI_STATE" in
      SUCCESS|success) CI_LABEL="✓ green" ;;
      FAILURE|failure) CI_LABEL="✗ FAILED" ;;
      pending|PENDING)  CI_LABEL="… running" ;;
      *)                CI_LABEL="$CI_STATE" ;;
    esac
    
    printf "  %-35s #%-5s %-10s %s\n" "$branch" "$PR_NUM" "$PR_STATE" "$CI_LABEL"
  done
fi

# ── 3. Pre-merge conflict simulation ─────────────────────────
echo ""
echo "▶ PRE-MERGE CONFLICT SIMULATION"
echo ""
echo "  Simulating merge of each branch against dev (no-commit, no-ff)..."
echo ""

# Save current state
ORIG_BRANCH="$(git branch --show-current 2>/dev/null || git rev-parse --short HEAD)"

# Refresh dev
git fetch origin --quiet 2>/dev/null || true
git checkout dev --quiet 2>/dev/null
git pull origin dev --quiet 2>/dev/null || true

CONFLICT_COUNT=0
for branch in $TASK_BRANCHES; do
  # Try the merge in-memory; abort regardless
  if git merge --no-commit --no-ff "origin/$branch" --quiet >/dev/null 2>&1; then
    printf "  %-35s ✓ clean\n" "$branch"
    git merge --abort 2>/dev/null || true
  else
    printf "  %-35s ✗ CONFLICTS\n" "$branch"
    # List conflicting files
    git diff --name-only --diff-filter=U 2>/dev/null | sed 's/^/      → /' || true
    git merge --abort 2>/dev/null || true
    CONFLICT_COUNT=$((CONFLICT_COUNT + 1))
  fi
done

# Restore original branch
git checkout "$ORIG_BRANCH" --quiet 2>/dev/null || true

# ── 4. Agent log summary ─────────────────────────────────────
echo ""
echo "▶ AGENT LOGS (last 10 lines per agent)"
echo ""

if [ -d "$LOG_DIR" ]; then
  for log in "$LOG_DIR"/agent-*.log; do
    [ -f "$log" ] || continue
    AGENT="$(basename "$log" .log | sed 's/^agent-//')"
    echo "  ── $AGENT ──"
    tail -n 10 "$log" | sed 's/^/      /'
    echo ""
  done
else
  echo "  No log directory found ($LOG_DIR)"
fi

# ── 5. Summary ───────────────────────────────────────────────
echo ""
echo "▶ POST-REVIEW CHECKLIST"
echo ""
echo "  1. Review each PR diff in GitHub — check ## Assumptions section in particular"
echo "  2. Confirm CI green on every PR before merging"

if [ "$CONFLICT_COUNT" -gt 0 ]; then
  echo "  3. ⚠ $CONFLICT_COUNT branches have merge conflicts — resolve before merging"
else
  echo "  3. ✓ No merge conflicts detected"
fi

echo "  4. Merge ONE PR at a time — run \`php artisan test\` on dev after each merge"
echo "  5. Run /task-done for each merged task"
echo "  6. When all merged, run ./dispatch.sh [next-batch-name]"
echo ""
echo "════════════════════════════════════════════════════════════"
