#!/bin/bash
# loop.sh — ให้ Claude Code ทำงานทีละข้อใน PROGRESS.md วนไปจนเสร็จ หรือชนเพดานข้อใดข้อหนึ่ง
# ใช้: วางไฟล์นี้ + PROMPT.md + PROGRESS.md ไว้ที่ root ของ repo แล้วรัน ./loop.sh บน branch แยก
# ต้องมี: claude, jq, git
set -uo pipefail

MAX_ITER=${MAX_ITER:-10}               # เพดานจำนวนรอบ
MAX_TURNS=${MAX_TURNS:-40}             # เพดานเทิร์นต่อรอบ
BUDGET_PER_ITER=${BUDGET_PER_ITER:-1}  # เพดานเงินต่อรอบ (USD, ค่าประมาณฝั่ง client)
MAX_TOTAL_USD=${MAX_TOTAL_USD:-8}      # เพดานเงินรวมทั้งการรัน
MAX_NO_PROGRESS=${MAX_NO_PROGRESS:-2}  # ไม่มี commit ใหม่กี่รอบติดกันแล้วให้หยุด
HOOKS=${HOOKS:-.claude/loop-hooks.json} # Stop hook สำหรับ loop (บท 7d-03) — ไม่มีไฟล์ก็ข้าม
LOG_DIR=${LOG_DIR:-.loop-logs}

# tool ที่อนุญาต — แก้คำสั่งเทสต์ให้ตรงโปรเจกต์ (อย่าเพิ่ม git push หรือ rm)
ALLOWED=("Read" "Glob" "Grep" "Edit" "Write"
  "Bash(npm test *)" "Bash(git status *)" "Bash(git diff *)" "Bash(git log *)"
  "Bash(git add *)" "Bash(git commit *)")

branch=$(git branch --show-current)
case "$branch" in
  main|master|"") echo "ห้ามรันบน '$branch' — สร้าง branch แยกก่อน: git switch -c agent/loop" >&2; exit 1 ;;
esac
for f in PROMPT.md PROGRESS.md; do
  [ -f "$f" ] || { echo "ไม่พบ $f" >&2; exit 1; }
done
settings=()
[ -f "$HOOKS" ] && settings=(--settings "$HOOKS")

mkdir -p "$LOG_DIR"
total=0
stuck=0
for i in $(seq 1 "$MAX_ITER"); do
  if [ -f STOP ]; then echo "พบไฟล์ STOP — หยุด (ลบไฟล์ STOP ก่อนรันใหม่)"; break; fi
  if ! grep -q '^- \[ \]' PROGRESS.md; then echo "ไม่มีงาน - [ ] เหลือใน PROGRESS.md — เสร็จแล้ว"; break; fi
  if awk -v t="$total" -v m="$MAX_TOTAL_USD" 'BEGIN{exit !(t>=m)}'; then
    echo "ใช้เงินรวม ~\$$total ชนเพดาน \$$MAX_TOTAL_USD — หยุด"; break
  fi

  before=$(git rev-parse HEAD)
  log="$LOG_DIR/$(date +%Y%m%d-%H%M%S)-$i.json"
  echo "== รอบ $i/$MAX_ITER เริ่ม $(date +%H:%M:%S) =="

  # < /dev/null: ไม่ให้ claude รอ stdin · prompt ต้องมาก่อน --allowedTools ที่รับได้หลายค่า
  claude -p "$(cat PROMPT.md)" \
    --output-format json \
    --permission-mode dontAsk \
    --max-turns "$MAX_TURNS" \
    --max-budget-usd "$BUDGET_PER_ITER" \
    ${settings[@]+"${settings[@]}"} \
    --allowedTools "${ALLOWED[@]}" \
    < /dev/null > "$log"
  code=$?

  cost=$(jq -r '.total_cost_usd // 0 | . * 100 | round / 100' "$log" 2>/dev/null || echo 0)
  total=$(awk -v a="$total" -v b="$cost" 'BEGIN{printf "%.2f", a+b}')
  echo "   exit=$code subtype=$(jq -r '.subtype // "?"' "$log" 2>/dev/null) turns=$(jq -r '.num_turns // "?"' "$log" 2>/dev/null) cost≈\$$cost รวม≈\$$total"

  if [ "$(git rev-parse HEAD)" = "$before" ]; then
    stuck=$((stuck + 1))
    echo "   ไม่มี commit ใหม่ ($stuck/$MAX_NO_PROGRESS)"
    if [ "$stuck" -ge "$MAX_NO_PROGRESS" ]; then echo "ไม่คืบหน้า — หยุดให้คนมาดู"; break; fi
  else
    stuck=0
    git log --oneline -1 | sed 's/^/   commit: /'
  fi
done

echo "== จบ: รวม≈\$$total · log อยู่ใน $LOG_DIR · ตรวจงานด้วย git log --oneline และ git diff main...HEAD =="
