#!/bin/bash
# Final CC setup for Hybrid Protocol

REPO_PATH="/root/rateright-growth"
CC_DIR="$REPO_PATH/.claude"

echo "=== Final CC Setup ==="

# 1. Update INBOX.md with Hybrid Protocol format
echo "1. Updating INBOX.md with Hybrid Protocol format..."
cat > "$CC_DIR/INBOX.md" << 'EOF'
# INBOX.md - Tasks for Claude Code (Hybrid Protocol)

## PENDING
<!-- Rivet adds tasks here -->

## IN PROGRESS
<!-- CC moves tasks here when working -->

## REVIEW REQUESTED
<!-- CC moves tasks here when ready for Rivet review -->

## COMPLETED
<!-- CC moves approved tasks here -->

## FAILED
<!-- CC moves failed/timeout tasks here -->

## APPROVALS
<!-- Rivet adds approval decisions here -->
EOF

# 2. Update OUTBOX.md with REVIEW REQUEST format
echo "2. Updating OUTBOX.md with REVIEW REQUEST format..."
cat > "$CC_DIR/OUTBOX.md" << 'EOF'
# OUTBOX.md - Output from Claude Code

## REVIEW REQUESTS
<!-- CC adds review requests here -->

## LATEST OUTPUT
<!-- CC writes results here -->
EOF

# 3. Update STATUS.md
echo "3. Updating STATUS.md..."
cat > "$CC_DIR/STATUS.md" << 'EOF'
# STATUS.md - Claude Code Status

**Current Status**: idle
**Last Check**: 
**Queue**: 0 pending tasks
**Health**: ok
**Protocol**: hybrid
**Version**: 1.0
EOF

# 4. Create final cc-poll script
echo "4. Creating final cc-poll script..."
cat > /usr/local/bin/cc-poll << 'EOF'
#!/bin/bash
# CC polling daemon for Hybrid Protocol

REPO_PATH="/root/rateright-growth"
CC_DIR="$REPO_PATH/.claude"
LOG_FILE="$CC_DIR/cc-poll.log"
TIMEOUT_MINUTES=30

log() {
  echo "$(date '+%Y-%m-%d %H:%M:%S') $1" >> "$LOG_FILE"
}

process_pending_task() {
  local task_line="$1"
  local task_id=$(echo "$task_line" | sed 's/^### Task: //' | awk '{print $1}')
  local task_type=$(echo "$task_line" | grep -o "Type: [^|]*" | cut -d: -f2 | xargs)
  
  log "Processing task: $task_id ($task_type)"
  
  # Move from PENDING to IN PROGRESS
  sed -i "/^### Task: $task_id$/,/^$/d" "$CC_DIR/INBOX.md"
  sed -i "/^## IN PROGRESS$/a\\
### Task: $task_id\\
**Type**: $task_type\\
**Started**: $(date)\\
**Status**: working" "$CC_DIR/INBOX.md"
  
  # Update STATUS
  sed -i "s/Current Status: idle/Current Status: working/" "$CC_DIR/STATUS.md"
  sed -i "s/Last Check: .*/Last Check: $(date)/" "$CC_DIR/STATUS.md"
  
  # Run CC (simulated for now - need actual CC installation)
  log "Would run CC for task $task_id"
  sleep 2  # Simulate work
  
  # Move to REVIEW REQUESTED with output
  sed -i "/^### Task: $task_id$/,/^$/d" "$CC_DIR/INBOX.md"
  sed -i "/^## REVIEW REQUESTED$/a\\
### Task: $task_id\\
**Type**: $task_type\\
**Completed**: $(date)\\
**Status**: review_requested" "$CC_DIR/INBOX.md"
  
  # Add to OUTBOX.md
  cat >> "$CC_DIR/OUTBOX.md" << REVIEW

## REVIEW REQUEST
Task: $task_id
Type: $task_type
Priority: P2

### Changes
- Simulated fix for testing

### Testing Done
- [x] Manual test: simulated
- [x] Existing tests pass

### Confidence
MEDIUM - simulated test

### Ready to Push?
Awaiting Rivet approval.
REVIEW
  
  # Update STATUS
  sed -i "s/Current Status: working/Current Status: idle/" "$CC_DIR/STATUS.md"
  
  # Git commit
  cd "$REPO_PATH"
  git add "$CC_DIR"/*.md 2>/dev/null
  git commit -m "CC: Task $task_id ready for review" 2>/dev/null || true
  git push origin main 2>/dev/null || true
  
  log "Task $task_id ready for review"
}

check_approvals() {
  # Check for new approvals from Rivet
  if grep -q "^## APPROVAL:" "$CC_DIR/INBOX.md"; then
    local approval_line=$(grep -m1 "^## APPROVAL:" "$CC_DIR/INBOX.md")
    local task_id=$(echo "$approval_line" | sed 's/## APPROVAL: //' | awk '{print $1}')
    local decision=$(echo "$approval_line" | grep -o "Decision: [^|]*" | cut -d: -f2 | xargs)
    
    if [ "$decision" = "✅ APPROVED" ]; then
      log "Approval found for $task_id - marking completed"
      # Move from REVIEW REQUESTED to COMPLETED
      sed -i "/^### Task: $task_id$/,/^$/d" "$CC_DIR/INBOX.md"
      sed -i "/^## COMPLETED$/a\\
### Task: $task_id\\
**Type**: bug_fix\\
**Approved**: $(date)\\
**Status**: completed" "$CC_DIR/INBOX.md"
      
      # Git commit
      cd "$REPO_PATH"
      git add "$CC_DIR"/*.md 2>/dev/null
      git commit -m "CC: Task $task_id approved and completed" 2>/dev/null || true
      git push origin main 2>/dev/null || true
    fi
  fi
}

main_loop() {
  while true; do
    cd "$REPO_PATH"
    git pull origin main 2>/dev/null
    
    # Check for pending tasks
    if [ -f "$CC_DIR/INBOX.md" ]; then
      # Get first pending task
      task_line=$(sed -n '/^## PENDING$/,/^##/p' "$CC_DIR/INBOX.md" | grep -m1 "^### Task:")
      if [ -n "$task_line" ]; then
        process_pending_task "$task_line"
      fi
    fi
    
    # Check for approvals
    check_approvals
    
    sleep 60  # Check every minute for testing
  done
}

# Start
log "CC Poll daemon started with Hybrid Protocol"
main_loop
EOF

chmod +x /usr/local/bin/cc-poll

# 5. Update systemd service
echo "5. Updating systemd service..."
cat > /etc/systemd/system/cc-poll.service << 'EOF'
[Unit]
Description=Claude Code Polling Daemon (Hybrid Protocol)
After=network.target

[Service]
Type=simple
User=ccuser
WorkingDirectory=/root/rateright-growth
ExecStart=/usr/local/bin/cc-poll
Restart=always
RestartSec=10
StandardOutput=append:/root/rateright-growth/.claude/cc-poll.log
StandardError=append:/root/rateright-growth/.claude/cc-poll.log

[Install]
WantedBy=multi-user.target
EOF

# 6. Create Rivet approval script
echo "6. Creating Rivet approval script..."
cat > /root/clawd/scripts/rivet-approve.sh << 'EOF'
#!/bin/bash
# Rivet approval functions for Hybrid Protocol

REPO_PATH="/root/rateright-growth"
CC_DIR="$REPO_PATH/.claude"

rivet_approve_task() {
  local task_id="$1"
  local feedback="${2:-Looks good. Push it.}"
  
  cd "$REPO_PATH"
  git pull origin main 2>/dev/null
  
  # Add approval to INBOX.md
  cat >> "$CC_DIR/INBOX.md" << APPROVAL

## APPROVAL: $task_id
Decision: ✅ APPROVED
Feedback: $feedback
Approved at: $(date)
Next: CC should push to main and mark task DONE.
APPROVAL
  
  git add "$CC_DIR/INBOX.md"
  git commit -m "Rivet: Approved task $task_id" 2>/dev/null || true
  git push origin main 2>/dev/null || true
  
  echo "Approved task $task_id"
}

rivet_reject_task() {
  local task_id="$1"
  local feedback="$2"
  
  cd "$REPO_PATH"
  git pull origin main 2>/dev/null
  
  cat >> "$CC_DIR/INBOX.md" << REJECTION

## APPROVAL: $task_id
Decision: 🔄 REVISE
Feedback: $feedback
Rejected at: $(date)
Next: CC should revise and resubmit.
REJECTION
  
  git add "$CC_DIR/INBOX.md"
  git commit -m "Rivet: Revision needed for task $task_id" 2>/dev/null || true
  git push origin main 2>/dev/null || true
  
  echo "Requested revision for task $task_id"
}

rivet_assign_task() {
  local task_type="$1"
  local description="$2"
  local priority="${3:-P2}"
  local task_id="TASK-$(date '+%Y%m%d-%H%M%S')"
  
  cd "$REPO_PATH"
  git pull origin main 2>/dev/null
  
  # Add task to PENDING
  sed -i "/^## PENDING$/a\\
### Task: $task_id\\
**Type**: $task_type\\
**Priority**: $priority\\
**Assigned**: $(date)\\
**Description**: $description\\
**Status**: pending" "$CC_DIR/INBOX.md"
  
  git add "$CC_DIR/INBOX.md"
  git commit -m "Rivet: Assigned task $task_id" 2>/dev/null || true
  git push origin main 2>/dev/null || true
  
  echo "Assigned task $task_id to CC"
  echo "Task ID: $task_id"
}

# Check CC status
rivet_cc_status() {
  if [ -f "$CC_DIR/STATUS.md" ]; then
    echo "CC Status:"
    grep -E "Current Status|Last Check|Queue|Health" "$CC_DIR/STATUS.md"
  else
    echo "CC status unknown"
  fi
}

# Check pending tasks
rivet_pending_tasks() {
  if [ -f "$CC_DIR/INBOX.md" ]; then
    echo "Pending tasks:"
    sed -n '/^## PENDING$/,/^##/p' "$CC_DIR/INBOX.md" | grep "^### Task:" | wc -l
  fi
}
EOF

chmod +x /root/clawd/scripts/rivet-approve.sh

# 7. Start the service
echo "7. Starting cc-poll service..."
systemctl daemon-reload
systemctl enable cc-poll
systemctl start cc-poll

sleep 2
echo "8. Checking service status..."
systemctl status cc-poll --no-pager | head -20

echo ""
echo "=== Hybrid Protocol Setup Complete ==="
echo ""
echo "Usage:"
echo "1. Assign task:   ./rivet-approve.sh rivet_assign_task 'bug_fix' 'Login broken' 'P1'"
echo "2. Check status:  ./rivet-approve.sh rivet_cc_status"
echo "3. Approve task:  ./rivet-approve.sh rivet_approve_task 'TASK-...' 'Looks good'"
echo "4. Reject task:   ./rivet-approve.sh rivet_reject_task 'TASK-...' 'Needs more tests'"
echo ""
echo "Note: CC needs to be installed for ccuser for real execution"
echo "Current setup uses simulated processing for testing"