#!/bin/bash
#
# Main development mode - intelligent task selection with parallel execution
# Usage: claudefsd-dev [--working-dir=DIR] [--max-time=MINUTES]
#
# Options:
#   --working-dir=DIR    Directory containing BRIEF.md and PLAN.md (default: docs)
#   --max-time=MINUTES   Maximum total runtime in minutes (default: 120)
#
# Features:
# - Fail-fast loop detection and "all done" prompt from iterative mode
# - Direct parallel Task agent execution from direct mode
# - Intelligent task planning and coordination
# - @STOP marker support: stops when all tasks before @STOP are complete
# - Max runtime limit to prevent runaway sessions
#

#set -e

# Parse command line parameters
WORKING_DIR="docs"
MAX_TIME_MINUTES=120
for arg in "$@"; do
    case $arg in
        --working-dir=*)
            WORKING_DIR="${arg#*=}"
            shift
            ;;
        --max-time=*)
            MAX_TIME_MINUTES="${arg#*=}"
            shift
            ;;
    esac
done
export CLAUDEFSD_WORKING_DIR="$WORKING_DIR"

# Convert max time to seconds and record start time
MAX_TIME_SECONDS=$((MAX_TIME_MINUTES * 60))
OVERALL_START_TIME=$(date +%s)

# Get the actual location of this script (resolving symlinks)
if command -v realpath >/dev/null 2>&1; then
    SCRIPT_PATH="$(realpath "$0")"
elif command -v readlink >/dev/null 2>&1; then
    # macOS doesn't have realpath by default, but has readlink
    SCRIPT_PATH="$0"
    while [ -L "$SCRIPT_PATH" ]; do
        SCRIPT_PATH="$(readlink "$SCRIPT_PATH")"
    done
    SCRIPT_PATH="$(cd "$(dirname "$SCRIPT_PATH")" && pwd)/$(basename "$SCRIPT_PATH")"
else
    # Fallback if neither command is available
    SCRIPT_PATH="$(cd "$(dirname "$0")" && pwd)/$(basename "$0")"
fi

# Get the directory containing the script
SCRIPT_DIR="$(dirname "$SCRIPT_PATH")"

# Check dependencies
"$SCRIPT_DIR/claudefsd-check-dependencies"

# Function to check for required files
check_requirements() {
    # Load file finding functions
    source "$SCRIPT_DIR/claudefsd-find-brief"
    brief_file=$(find_brief_file 2>/dev/null || echo "")

    if [ -z "$brief_file" ]; then
        echo "No BRIEF.md file found in $WORKING_DIR/ or root directory. Please create one first."
        exit 1
    fi

    plan_file=$(find_project_file "PLAN.md" 2>/dev/null || echo "")
    if [ -z "$plan_file" ]; then
        echo "No PLAN.md file found in $WORKING_DIR/ or root directory. Please run 'claudefsd create-plan' first."
        exit 1
    fi
}

# Check requirements
check_requirements

# Add counter for loop iterations
LOOP_COUNTER=0

# Failure detection variables
CONSECUTIVE_FAST_ITERATIONS=0
MIN_ITERATION_TIME=300  # 5 minutes in seconds

# Test command cache (in-memory, asked once per session)
TEST_COMMAND=""
LAST_TEST_OUTPUT=""

while true; do
    # Record iteration start time
    ITERATION_START_TIME=$(date +%s)
    
    # Increment loop counter
    LOOP_COUNTER=$((LOOP_COUNTER + 1))
    
    mkdir -p logs
    # Use a temporary directory for tmp files
    mkdir -p tmp
    export TMPDIR=tmp/
    LOGFILE="logs/claude-dev-$(date +%Y%m%d_%H%M%S).txt"

    echo "Logging to ${LOGFILE} ..."

    echo -e "\033[32m==================================================================\033[0m"
    echo -e "\033[32m== DEVELOPMENT MODE - ITERATION $LOOP_COUNTER\033[0m"
    echo -e "\033[32m==================================================================\033[0m"

    # Check if this is the 4th iteration for megathinking mode
    if [ $((LOOP_COUNTER % 4)) -eq 0 ]; then
        echo -e "\033[33m**** MEGATHINKING MODE ACTIVATED ****\033[0m"
        echo -e "\033[33mThis is your 4th development cycle. Taking a step back for architectural planning.\033[0m"
        MEGATHINKING_MODE="<ultrathink>
**** MEGATHINKING MODE ACTIVATED ****
This is your 4th development cycle. Before proceeding with the next task, engage in deep extended reasoning to:
- Take a step back and architecturally plan the next phase of development
- Consider the overall structure of the codebase
- Identify potential refactoring opportunities
- Evaluate design patterns and technical debt
- Think about how the current work connects to broader project goals
- Analyze edge cases and potential failure modes
Take your time to think deeply about the optimal approach before proceeding.
</ultrathink>

"
        CLAUDE_MODEL="opus"
    else
        MEGATHINKING_MODE=""
        CLAUDE_MODEL="opus"
    fi

    # Build the development prompt combining intelligent task selection with parallel execution
    DEVELOPMENT_PROMPT="$MEGATHINKING_MODE
You are an elite AI developer working in an automated development environment. Your job is to IMPLEMENT tasks from the project plan, not just analyze them. You can either implement tasks directly yourself or coordinate parallel Task agents for independent work.

**PROJECT FILES TO READ AND ANALYZE:**"

    # Build file list using flexible file detection
    source "$SCRIPT_DIR/claudefsd-find-brief"

    brief_file=$(find_brief_file 2>/dev/null || echo "")
    if [ -n "$brief_file" ]; then
        DEVELOPMENT_PROMPT="$DEVELOPMENT_PROMPT
- $brief_file (project brief)"
    fi

    plan_file=$(find_project_file "PLAN.md" 2>/dev/null || echo "")
    if [ -n "$plan_file" ]; then
        DEVELOPMENT_PROMPT="$DEVELOPMENT_PROMPT
- $plan_file (development plan with tasks)"
    fi

    requirements_file=$(find_project_file "REQUIREMENTS.md" 2>/dev/null || echo "")
    if [ -n "$requirements_file" ]; then
        DEVELOPMENT_PROMPT="$DEVELOPMENT_PROMPT
- $requirements_file (project requirements)"
    fi

    questions_file=$(find_project_file "QUESTIONS.md" 2>/dev/null || echo "")
    if [ -n "$questions_file" ]; then
        DEVELOPMENT_PROMPT="$DEVELOPMENT_PROMPT
- $questions_file (interview Q&A)"
    fi

    notes_file=$(find_project_file "CLAUDE-NOTES.md" 2>/dev/null || echo "")
    if [ -n "$notes_file" ]; then
        DEVELOPMENT_PROMPT="$DEVELOPMENT_PROMPT
- $notes_file (technical notes)"
    fi

    readme_file=$(find_project_file "README.md" 2>/dev/null || echo "")
    if [ -n "$readme_file" ]; then
        DEVELOPMENT_PROMPT="$DEVELOPMENT_PROMPT
- $readme_file (project readme)"
    fi
    
    if [ -f "CLAUDE.md" ]; then
        DEVELOPMENT_PROMPT="$DEVELOPMENT_PROMPT
- CLAUDE.md (project-specific instructions)"
    fi
    
    if [ -f "$HOME/.claude/CLAUDE.md" ]; then
        DEVELOPMENT_PROMPT="$DEVELOPMENT_PROMPT
- $HOME/.claude/CLAUDE.md (global development principles)"
    fi

    # Check for human feedback file
    feedback_file=$(find_project_file "FEEDBACK.md" 2>/dev/null || echo "")
    if [ -n "$feedback_file" ]; then
        DEVELOPMENT_PROMPT="$DEVELOPMENT_PROMPT
- $feedback_file (URGENT: Human feedback requiring immediate attention)"
    fi

    # Add failed test output if tests failed last iteration
    if [ -n "$LAST_TEST_OUTPUT" ]; then
        DEVELOPMENT_PROMPT="$DEVELOPMENT_PROMPT

**URGENT: UNIT TESTS FAILED LAST ITERATION - FIX BEFORE CONTINUING**
The following test output shows what failed. Fix these issues first:
\`\`\`
$LAST_TEST_OUTPUT
\`\`\`"
    fi

    DEVELOPMENT_PROMPT="$DEVELOPMENT_PROMPT

**IMPORTANT:** Before starting ANY work, you MUST read and understand:
1. The project's CLAUDE.md file (if it exists) - this contains project-specific instructions
2. The user's global CLAUDE.md file at \$HOME/.claude/CLAUDE.md (if it exists) - this contains general development principles
3. If FEEDBACK.md exists, READ IT FIRST - it contains urgent human feedback that takes priority
4. Read the '## Test Infrastructure' section in $plan_file for test commands
5. Ensure all your work follows the architectural and development guidelines from both files

**CRITICAL ANTI-PATTERNS TO AVOID (from CLAUDE.md):**
- NO CHEATING: Never disable tests, exclude files from compilation, or use silent fallbacks
- FAIL FAST: Integration failures should throw exceptions, not return mock data
- NO PRODUCTION FALLBACKS: Avoid try/catch blocks that hide errors with default values
- NO BACKUP COPIES: Use git for version control, never create backup files
- DELETE OLD CODE: Remove unused functions and scripts, keep the codebase clean

**YOUR MISSION:**

**PHASE 1: TASK SELECTION**
1. Read $plan_file and work through tasks in order
2. If a phase references a sub-plan file, read that file as well
3. Complete tasks in the order they appear - don't skip ahead
4. Identify if tasks can be done in parallel

**PHASE 2: EXECUTION STRATEGY (TDD REQUIRED)**
You MUST follow Test-Driven Development:

1. **RED**: Write a failing test first that defines the expected behavior
2. **GREEN**: Write the minimum code to make the test pass
3. **REFACTOR**: Clean up the code while keeping tests passing

For each task:
- Write the test BEFORE writing implementation code
- Run tests using commands from '## Test Infrastructure' in $plan_file
- Only mark task complete after tests pass

**Option A: Single Focus Task** (for sequential dependencies or complex architectural work)
- Follow TDD cycle for the next task
- Update $plan_file to mark task as complete with [x] ONLY after tests pass

**Option B: Parallel Task Execution** (for independent tasks)
- Each parallel agent must also follow TDD
- Coordinate the parallel work to ensure test consistency

**PHASE 3: COMPLETION CHECK**
After completing work:
1. Run ALL tests to verify nothing is broken
2. Update $plan_file to reflect completed tasks (only if tests pass)
3. Report on what was accomplished and what remains

**EXECUTION GUIDELINES:**
- **BUILD BULLETPROOF**: Create robust solutions that handle edge cases
- **STAY FOCUSED**: Only implement what's specified in $plan_file
- **QUALITY FIRST**: Proper error handling, testing, and documentation
- **ARCHITECTURAL THINKING**: Consider long-term maintainability

**TASK AGENT COORDINATION:**
When using parallel Task agents, ensure each one:
- Has full project context and understands the architecture
- Knows about related components they might need to integrate with
- Follows all CLAUDE.md guidelines
- Implements consistent code style and patterns
- Handles proper error checking and edge cases

**OUTPUT FORMAT:**
1. **<task_analysis>**: List identified open tasks and selected approach
2. **<execution>**: Details of your ACTUAL implementation work (code written, files edited, commands run)
3. **<plan_updates>**: How you updated $plan_file to reflect progress
4. **<completion_check>**: Status of remaining work

IMPORTANT: You must ACTUALLY IMPLEMENT tasks, not just describe what should be done. Use Edit, Write, Bash, and Task tools to complete real work. Begin by analyzing $plan_file and then IMPLEMENT the next task in order."

    # Save the prompt to the log file and print to screen
    echo "=== DEVELOPMENT PROMPT ===" | tee $LOGFILE
    echo "$DEVELOPMENT_PROMPT" | tee -a $LOGFILE
    echo "=== END PROMPT ===" | tee -a $LOGFILE
    echo "" >> $LOGFILE
    echo "=== OUTPUT ===" >> $LOGFILE

    # Run claude and append output to the log file
    # Raw JSON goes to log, filtered text to screen
    # Use stdin instead of -p to avoid "Argument list too long" errors
    echo -e "\033[36mRunning development with $CLAUDE_MODEL model...\033[0m"
    time echo "$DEVELOPMENT_PROMPT" | claude --model $CLAUDE_MODEL --print --verbose --output-format=stream-json --include-partial-messages --dangerously-skip-permissions 2>&1 | tee -a $LOGFILE | jq -R --unbuffered -r '. as $line | try (fromjson | if .type == "assistant" then (.message.content[]? | if .type == "text" then .text elif .type == "tool_use" then "\n[TOOL: " + .name + "]\n" else empty end) // empty elif .type == "stream_event" and .event == "content_block_start" and .content_block.type == "tool_use" then "\n[TOOL: " + .content_block.name + "]\n" elif .type == "result" then "\n=== RESULT ===\n" + (.result // "no result") else empty end) catch $line'

    # Extract what task was worked on from the developer's output
    DEVELOPER_OUTPUT=$(sed -n '/=== OUTPUT ===/,$p' $LOGFILE)

    echo -e "\033[32m==================================================================\033[0m"
    echo -e "\033[32m== REVIEWING/VERIFYING WORK\033[0m"
    echo -e "\033[32m==================================================================\033[0m"

    # Define the verifier prompt - CODE REVIEW ONLY, no test running
    VERIFIER_PROMPT="You are an expert code reviewer. Your job is CODE REVIEW and GIT COMMITS only.
DO NOT run tests - a separate Tester agent will handle that.

**DEVELOPER'S OUTPUT:**
$DEVELOPER_OUTPUT

**YOUR TASKS:**
1. Review what the developer claims to have done
2. Verify the work was actually completed by checking files
3. Look for cheating patterns (disabled tests, silent fallbacks, mock data, etc.)
4. Check code quality: proper error handling, no obvious bugs
5. Create a git commit (see guidelines below)

**CODE REVIEW CHECKLIST:**
- Did the developer actually implement code (not just analyze)?
- Did the developer follow TDD (wrote tests before implementation)?
- Are there any cheating patterns or anti-patterns?
- Is the code well-structured and maintainable?
- Is the task properly marked as complete in $plan_file?

**GIT COMMIT GUIDELINES:**
- If the code looks good: Definitely commit with a clear message
- If the code has issues but isn't completely broken: Still commit (git is our backup) but note issues in commit message
- If there are many pending changes: Always commit to avoid losing work
- Only skip commit if changes are truly destructive/terrible
- Use descriptive commit messages that explain what was attempted

**IMPORTANT:**
- DO NOT run tests - the Tester agent will do that next
- If you find code quality issues, describe them clearly in your review AND in the commit message
- Focus on code review, not test verification

Be thorough but concise in your code review."

    VERIFIER_LOGFILE="${LOGFILE}-verifier"
    echo "=== VERIFIER PROMPT ===" | tee $VERIFIER_LOGFILE
    echo "$VERIFIER_PROMPT" | tee -a $VERIFIER_LOGFILE
    echo "=== END PROMPT ===" | tee -a $VERIFIER_LOGFILE
    echo "" >> $VERIFIER_LOGFILE
    echo "=== OUTPUT ===" >> $VERIFIER_LOGFILE

    # Run verifier
    # Raw JSON goes to log, filtered text to screen
    # Use stdin instead of -p to avoid "Argument list too long" errors
    echo -e "\033[36mRunning verifier with $CLAUDE_MODEL model...\033[0m"
    time echo "$VERIFIER_PROMPT" | claude --model $CLAUDE_MODEL --print --verbose --output-format=stream-json --include-partial-messages --dangerously-skip-permissions 2>&1 | tee -a $VERIFIER_LOGFILE | jq -R --unbuffered -r '. as $line | try (fromjson | if .type == "assistant" then (.message.content[]? | if .type == "text" then .text elif .type == "tool_use" then "\n[TOOL: " + .name + "]\n" else empty end) // empty elif .type == "stream_event" and .event == "content_block_start" and .content_block.type == "tool_use" then "\n[TOOL: " + .content_block.name + "]\n" elif .type == "result" then "\n=== RESULT ===\n" + (.result // "no result") else empty end) catch $line'

    # Extract verifier output for the tester
    VERIFIER_OUTPUT=$(sed -n '/=== OUTPUT ===/,$p' $VERIFIER_LOGFILE)

    echo -e "\033[32m==================================================================\033[0m"
    echo -e "\033[32m== TESTING PHASE\033[0m"
    echo -e "\033[32m==================================================================\033[0m"

    TESTER_LOGFILE="${LOGFILE}-tester"
    UNIT_TESTS_PASSED=false

    # ========== UNIT TESTS (bash-driven, every iteration) ==========

    # Get test command if not cached
    if [ -z "$TEST_COMMAND" ]; then
        echo -e "\033[36mAsking Claude for test command (one-time per session)...\033[0m"

        TEST_QUERY="Read $plan_file and any project config files (package.json, pyproject.toml, Makefile, etc).
What is the single shell command to run unit tests for this project?

Reply with ONLY the command, nothing else. Examples of valid responses:
- pytest
- npm test
- cargo test
- make test
- go test ./...

If there are no tests configured yet, reply with: NO_TESTS"

        TEST_COMMAND=$(echo "$TEST_QUERY" | claude --model haiku --print 2>/dev/null | tail -1 | tr -d '\n\r')

        if [ -z "$TEST_COMMAND" ]; then
            TEST_COMMAND="NO_TESTS"
        fi

        echo -e "\033[36mCached test command: $TEST_COMMAND\033[0m"
    fi

    # Run unit tests directly (fast, no AI overhead)
    if [ "$TEST_COMMAND" = "NO_TESTS" ]; then
        echo -e "\033[33mNo test infrastructure found - skipping unit tests\033[0m"
        echo "No test infrastructure configured" >> $TESTER_LOGFILE
        UNIT_TESTS_PASSED=true  # Don't block on missing tests, but developer should add them
    else
        echo -e "\033[36mRunning: $TEST_COMMAND\033[0m"
        echo "=== UNIT TEST OUTPUT ===" >> $TESTER_LOGFILE

        if eval "$TEST_COMMAND" >> $TESTER_LOGFILE 2>&1; then
            echo -e "\033[32m✓ Unit tests PASSED\033[0m"
            UNIT_TESTS_PASSED=true
            LAST_TEST_OUTPUT=""
        else
            echo -e "\033[31m✗ Unit tests FAILED\033[0m"
            UNIT_TESTS_PASSED=false
            # Capture last 100 lines for developer feedback
            LAST_TEST_OUTPUT=$(tail -100 $TESTER_LOGFILE)
            echo -e "\033[31mTest output saved - will be provided to developer next iteration\033[0m"
        fi
    fi

    # ========== ACCEPTANCE TESTS (AI-driven, every 4th iteration) ==========

    if [ $((LOOP_COUNTER % 4)) -eq 0 ]; then
        echo -e "\033[33m== Running acceptance tests (4th iteration) ==\033[0m"

        ACCEPTANCE_PROMPT="You are a QA engineer checking acceptance criteria.

Read the '## Acceptance Criteria' section in $plan_file.
For each criterion:
1. Verify if it passes (run commands, check files, test endpoints as needed)
2. Mark passing criteria with [x] in the plan file
3. If a previously-passing criterion now FAILS, add: \`- [ ] [BUG] <description>\`

Also check: Are ALL tasks in $plan_file complete? If yes AND all acceptance criteria pass, output exactly:
<VERIFIED_ALL_DONE>

Be concise in your output."

        echo "=== ACCEPTANCE TEST OUTPUT ===" >> $TESTER_LOGFILE
        echo "$ACCEPTANCE_PROMPT" | claude --model $CLAUDE_MODEL --print --dangerously-skip-permissions 2>&1 | tee -a $TESTER_LOGFILE

        # Check if all done
        if grep -q "<VERIFIED_ALL_DONE>" $TESTER_LOGFILE; then
            echo -e "\033[32m==================================================================\033[0m"
            echo -e "\033[32m== PROJECT COMPLETE - ALL TASKS VERIFIED!\033[0m"
            echo -e "\033[32m==================================================================\033[0m"
            exit 0
        fi
    fi

    # If unit tests failed, continue to next iteration (developer needs to fix)
    if [ "$UNIT_TESTS_PASSED" = false ]; then
        echo -e "\033[31m==================================================================\033[0m"
        echo -e "\033[31m== UNIT TESTS FAILED - Developer will fix next iteration\033[0m"
        echo -e "\033[31m==================================================================\033[0m"
        # LAST_TEST_OUTPUT is set above, will be fed to developer in next iteration
    fi

    # Check for @STOP marker in plan file - if all tasks before @STOP are complete, pause for human review
    if [ -n "$plan_file" ] && grep -q "@STOP" "$plan_file"; then
        # Extract content before @STOP and check if any tasks are incomplete
        BEFORE_STOP=$(sed -n '1,/@STOP/p' "$plan_file")
        # Check for incomplete tasks ([ ] or - [ ]) before @STOP
        if ! echo "$BEFORE_STOP" | grep -qE '\[ \]'; then
            echo -e "\033[33m==================================================================\033[0m"
            echo -e "\033[33m== @STOP CHECKPOINT REACHED\033[0m"
            echo -e "\033[33m==================================================================\033[0m"
            echo -e "\033[33mAll tasks before @STOP marker are complete.\033[0m"
            echo -e "\033[33mPausing for human review/deployment/intervention.\033[0m"
            echo -e "\033[33mTo continue: remove or move @STOP in $plan_file, then restart.\033[0m"
            echo -e "\033[33m==================================================================\033[0m"
            exit 0
        fi
    fi

    # Check if max runtime has been exceeded
    CURRENT_TIME=$(date +%s)
    ELAPSED_SECONDS=$((CURRENT_TIME - OVERALL_START_TIME))
    ELAPSED_MINUTES=$((ELAPSED_SECONDS / 60))
    if [ $ELAPSED_SECONDS -ge $MAX_TIME_SECONDS ]; then
        echo -e "\033[33m==================================================================\033[0m"
        echo -e "\033[33m== MAX RUNTIME REACHED (${ELAPSED_MINUTES}m / ${MAX_TIME_MINUTES}m)\033[0m"
        echo -e "\033[33m==================================================================\033[0m"
        echo -e "\033[33mStopping after ${MAX_TIME_MINUTES} minutes as configured.\033[0m"
        echo -e "\033[33mTo continue: restart with 'claudefsd dev' or increase --max-time\033[0m"
        echo -e "\033[33m==================================================================\033[0m"
        exit 0
    fi
    echo -e "\033[36mTotal runtime: ${ELAPSED_MINUTES}m / ${MAX_TIME_MINUTES}m\033[0m"

    # Calculate iteration duration and check for failure patterns
    ITERATION_END_TIME=$(date +%s)
    ITERATION_DURATION=$((ITERATION_END_TIME - ITERATION_START_TIME))
    
    echo -e "\033[36mIteration $LOOP_COUNTER completed in ${ITERATION_DURATION}s\033[0m"
    
    # Check if iteration was suspiciously fast (likely failure mode)
    if [ $ITERATION_DURATION -lt $MIN_ITERATION_TIME ]; then
        CONSECUTIVE_FAST_ITERATIONS=$((CONSECUTIVE_FAST_ITERATIONS + 1))
        echo -e "\033[33mWarning: Fast iteration detected (${ITERATION_DURATION}s < ${MIN_ITERATION_TIME}s threshold)\033[0m"
        echo -e "\033[33mConsecutive fast iterations: $CONSECUTIVE_FAST_ITERATIONS/3\033[0m"
        
        # Exit if too many consecutive fast iterations (likely Claude API failure)
        if [ $CONSECUTIVE_FAST_ITERATIONS -ge 3 ]; then
            echo -e "\033[31m==================================================================\033[0m"
            echo -e "\033[31m== FAILURE MODE DETECTED - THROTTLING ACTIVATED\033[0m"
            echo -e "\033[31m==================================================================\033[0m"
            echo -e "\033[31mDetected 3 consecutive iterations under ${MIN_ITERATION_TIME}s each.\033[0m"
            echo -e "\033[31mThis usually indicates Claude API issues (token limits, etc).\033[0m"
            echo -e "\033[31m\033[0m"
            echo -e "\033[31mSuggested actions:\033[0m"
            echo -e "\033[31m- Check your Claude API token limits\033[0m"
            echo -e "\033[31m- Wait a few minutes and restart with: claudefsd dev\033[0m"
            echo -e "\033[31m- Review logs in: logs/\033[0m"
            echo -e "\033[31m==================================================================\033[0m"
            exit 1
        fi
        
        # Add exponential backoff delay for fast iterations
        BACKOFF_DELAY=$((CONSECUTIVE_FAST_ITERATIONS * 60))  # 1min, 2min, 3min
        echo -e "\033[33mApplying backoff delay: ${BACKOFF_DELAY}s\033[0m"
        sleep $BACKOFF_DELAY
    else
        # Reset counter on successful iteration
        CONSECUTIVE_FAST_ITERATIONS=0
        echo -e "\033[32mNormal iteration timing - continuing...\033[0m"
    fi

    # Check for PAUSE file - allows human intervention
    if [ -f "PAUSE" ]; then
        echo -e "\033[33m==================================================================\033[0m"
        echo -e "\033[33m== PAUSED - Human intervention requested\033[0m"
        echo -e "\033[33m==================================================================\033[0m"
        echo -e "\033[33mDevelopment is paused. To continue:\033[0m"
        echo -e "\033[33m  - Remove the PAUSE file: rm PAUSE\033[0m"
        echo -e "\033[33m  - Add feedback in $WORKING_DIR/FEEDBACK.md (optional)\033[0m"
        echo -e "\033[33mWaiting...\033[0m"
        while [ -f "PAUSE" ]; do
            sleep 5
        done
        echo -e "\033[32mResuming development...\033[0m"

        # Check if feedback was added
        if [ -f "$WORKING_DIR/FEEDBACK.md" ]; then
            echo -e "\033[36mFEEDBACK.md detected - will be processed in next iteration\033[0m"
        fi
    fi

    # Archive FEEDBACK.md after it's been processed (move to logs)
    if [ -n "$feedback_file" ] && [ -f "$feedback_file" ]; then
        mv "$feedback_file" "logs/FEEDBACK-processed-$(date +%Y%m%d_%H%M%S).md"
        echo -e "\033[36mFEEDBACK.md archived after processing\033[0m"
    fi

    sleep 1
done
