#!/bin/bash
# ralph.sh — Ralph Autonomous AI Agent Loop for Linux/Bash

TOOL="claude"
MAX_ITERATIONS=10

while [[ "$#" -gt 0 ]]; do
    case $1 in
        --tool) TOOL="$2"; shift ;;
        *) MAX_ITERATIONS="$1" ;;
    esac
    shift
done

echo -e "\e[32m🚀 Starting Ralph Autonomous Loop (Tool: $TOOL, Max: $MAX_ITERATIONS)\e[0m"

[ ! -f "progress.txt" ] && echo "--- Ralph Loop Progress Log ---" > progress.txt

if [ -f "prd.json" ]; then
    BRANCH=$(jq -r '.branchName' prd.json)
    [ ! -z "$BRANCH" ] && [ "$BRANCH" != "null" ] && {
        echo -e "\e[36m🌿 Checking out: $BRANCH\e[0m"
        git checkout "$BRANCH" 2>/dev/null || git checkout -b "$BRANCH"
    }
else
    echo -e "\e[31m❌ prd.json not found!\e[0m"; exit 1
fi

for ((i=1; i<=MAX_ITERATIONS; i++)); do
    echo -e "\n\e[33m🔄 --- Iteration $i of $MAX_ITERATIONS ---\e[0m"
    REMAINING=$(jq '[.userStories[] | select(.passes == false)] | length' prd.json)
    [ "$REMAINING" -eq 0 ] && { echo -e "\e[32m🎉 All done!\e[0m"; break; }

    NEXT_ID=$(jq -r '[.userStories[] | select(.passes == false)][0].id' prd.json)
    NEXT_TITLE=$(jq -r '[.userStories[] | select(.passes == false)][0].title' prd.json)
    echo -e "\e[36m🎯 Next: [$NEXT_ID] $NEXT_TITLE\e[0m"

    claude -p --dangerously-skip-permissions "Read scripts/ralph/CLAUDE.md and implement '$NEXT_ID: $NEXT_TITLE' from prd.json. Follow ALL rules in CLAUDE.md. Verify, commit, set passes:true, append learnings to progress.txt, output <promise>COMPLETE</promise>." 2>&1 | tee "scripts/ralph/last_iteration.log"
    git status -s
done

echo -e "\n\e[32m🏆 Ralph Loop Completed!\e[0m"

