#!/bin/bash
# OpenAgentsControl - Plan Executor
# 6-stage approval workflow: Analyze → Approve → Execute → Validate → Summarize → Confirm

set -e

# Configuration
PLAN_DIR="${PLAN_DIR:-.plan-executor}"
STAGE_FILE="$PLAN_DIR/current_stage.json"
LOG_FILE="$PLAN_DIR/execution.log"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m'

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

print_stage() {
    echo -e "${BLUE}[OpenAgentsControl]${NC} $1"
    log "$1"
}

print_success() {
    echo -e "${GREEN}[OpenAgentsControl]${NC} $1"
    log "SUCCESS: $1"
}

print_warning() {
    echo -e "${YELLOW}[OpenAgentsControl]${NC} $1"
    log "WARNING: $1"
}

print_error() {
    echo -e "${RED}[OpenAgentsControl]${NC} $1"
    log "ERROR: $1"
}

# Create plan directory
mkdir -p "$PLAN_DIR"

# Stage 1: Analyze
stage_analyze() {
    print_stage "Stage 1: ANALYZE"
    echo ""
    echo "Understanding request and assessing complexity..."
    echo ""

    # Save analysis
    cat > "$PLAN_DIR/analysis.json" << EOF
{
  "timestamp": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")",
  "request": "$1",
  "complexity": "assessing...",
  "affected_files": [],
  "risks": [],
  "needs_approval": true
}
EOF

    echo "✓ Analysis saved to $PLAN_DIR/analysis.json"
    echo ""
}

# Stage 2: Propose Plan
stage_plan() {
    print_stage "Stage 2: PROPOSE PLAN"
    echo ""
    echo "Creating implementation plan..."
    echo ""

    cat > "$PLAN_DIR/plan.md" << EOF
# Implementation Plan

**Created:** $(date -u +"%Y-%m-%d %H:%M:%SZ")

## Overview
$1

## Steps
1. [ ] Analyze requirements
2. [ ] Identify affected files
3. [ ] Create implementation
4. [ ] Test and validate
5. [ ] Document changes

## Risk Assessment
- Complexity: Medium
- Files affected: TBD
- Rollback strategy: git revert

## Estimated Resources
- Time: TBD
- Tokens: TBD

EOF

    echo "✓ Plan saved to $PLAN_DIR/plan.md"
    echo ""
    cat "$PLAN_DIR/plan.md"
    echo ""
}

# Stage 3: Await Approval
stage_approve() {
    print_stage "Stage 3: AWAIT APPROVAL"
    echo ""
    echo -e "${YELLOW}⚠️  REVIEW REQUIRED BEFORE PROCEEDING${NC}"
    echo ""
    echo "The following changes will be made:"
    echo "  • Files will be modified"
    echo "  • Git commits will be created"
    echo "  • Changes may be irreversible"
    echo ""
    echo "Type 'yes' to approve, 'no' to cancel, or 'modify' to change plan:"
    read -r approval

    case "$approval" in
        yes|y|YES)
            print_success "Approved! Proceeding with execution..."
            echo "true" > "$PLAN_DIR/approved"
            ;;
        no|n|NO)
            print_warning "Cancelled by user"
            echo "false" > "$PLAN_DIR/approved"
            exit 0
            ;;
        modify)
            print_warning "Modifying plan..."
            ${EDITOR:-nano} "$PLAN_DIR/plan.md"
            stage_approve
            ;;
        *)
            print_error "Invalid response. Please run again."
            exit 1
            ;;
    esac
}

# Stage 4: Execute
stage_execute() {
    print_stage "Stage 4: EXECUTE"
    echo ""
    echo "Implementing plan..."
    echo ""

    # Create backup
    git rev-parse HEAD > "$PLAN_DIR/pre_commit_hash" 2>/dev/null || true

    # Track execution
    cat > "$PLAN_DIR/execution.json" << EOF
{
  "timestamp": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")",
  "status": "in_progress",
  "steps_completed": []
}
EOF

    print_success "Execution tracking started"
}

# Stage 5: Validate
stage_validate() {
    print_stage "Stage 5: VALIDATE"
    echo ""
    echo "Running validation checks..."
    echo ""

    local checks_passed=0
    local checks_failed=0

    # Check if git status is clean
    if git diff --quiet 2>/dev/null; then
        echo "✓ Git status: Clean"
        ((checks_passed++))
    else
        echo "⚠ Git status: Has uncommitted changes"
        ((checks_failed++))
    fi

    # Run tests if available
    if [ -f "package.json" ] && grep -q "test" package.json; then
        echo "→ Running tests..."
        # npm test >> "$LOG_FILE" 2>&1 && echo "✓ Tests passed" && ((checks_passed++)) || echo "✗ Tests failed" && ((checks_failed++))
    fi

    # Run type check if available
    if command -v tsc &> /dev/null; then
        echo "→ Running type check..."
        # tsc --noEmit >> "$LOG_FILE" 2>&1 && echo "✓ Type check passed" && ((checks_passed++)) || echo "✗ Type check failed" && ((checks_failed++))
    fi

    echo ""
    print_success "Validation complete: $checks_passed passed, $checks_failed failed"

    cat > "$PLAN_DIR/validation.json" << EOF
{
  "timestamp": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")",
  "checks_passed": $checks_passed,
  "checks_failed": $checks_failed
}
EOF
}

# Stage 6: Summarize
stage_summarize() {
    print_stage "Stage 6: SUMMARIZE & CONFIRM"
    echo ""
    echo "Execution Summary"
    echo "================"
    echo ""

    if [ -f "$PLAN_DIR/pre_commit_hash" ]; then
        local pre_commit=$(cat "$PLAN_DIR/pre_commit_hash")
        echo "Started at: $pre_commit"
        echo ""
        echo "Changes made:"
        git log --oneline $pre_commit..HEAD 2>/dev/null || echo "No commits yet"
        echo ""
    fi

    if [ -f "$PLAN_DIR/validation.json" ]; then
        echo "Validation results:"
        cat "$PLAN_DIR/validation.json"
        echo ""
    fi

    print_success "Workflow complete! Results saved to $PLAN_DIR/"
}

# Main execution
main() {
    local request="$*"

    if [ -z "$request" ]; then
        print_error "Usage: $0 <request_description>"
        exit 1
    fi

    print_stage "OpenAgentsControl 6-Stage Workflow"
    echo "Request: $request"
    echo ""

    # Execute stages
    stage_analyze "$request"
    stage_plan "$request"
    stage_approve
    stage_execute
    stage_validate
    stage_summarize
}

main "$@"
