#!/bin/bash
# Setup Claude Code (CC) sync system via Git markdown files - CORRECTED

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

# Check if repo exists and is on main branch
if [ ! -d "$REPO_PATH/.git" ]; then
  echo "Error: Git repo not found at $REPO_PATH"
  exit 1
fi

cd "$REPO_PATH"
CURRENT_BRANCH=$(git branch --show-current)
if [ "$CURRENT_BRANCH" != "main" ]; then
  echo "Warning: Repo is on branch '$CURRENT_BRANCH', not 'main'"
fi

# Create sync files with correct format
cat > "$CC_DIR/INBOX.md" << 'EOF'
# INBOX.md - Tasks for Claude Code

## PENDING
<!-- Add tasks here -->

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

## COMPLETED
<!-- CC moves completed tasks here -->
EOF

cat > "$CC_DIR/OUTBOX.md" << 'EOF'
# OUTBOX.md - Output from Claude Code

## Latest Output
<!-- CC writes results here -->
EOF

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

**Current Status**: idle
**Last Check**: 
**Queue**: 0 pending tasks
**Health**: ok
EOF

# Create CC polling script for ccuser
cat > /usr/local/bin/cc-poll << 'EOF'
#!/bin/bash
# CC polling daemon - checks INBOX.md every 5 minutes
while true; do
  cd /root/rateright-growth
  git pull origin main 2>/dev/null
  
  if [ -f .claude/INBOX.md ]; then
    # Check for pending tasks in ## PENDING section
    if sed -n '/^## PENDING$/,/^##/p' .claude/INBOX.md | grep -q "^\#\#\# "; then
      echo "$(date): Found pending tasks in PENDING section"
      # Update status to working
      sed -i 's/Current Status: idle/Current Status: working/' .claude/STATUS.md
      sed -i "s/Last Check: .*/Last Check: $(date)/" .claude/STATUS.md
      
      # Run CC as ccuser (if installed for ccuser)
      if sudo -u ccuser command -v claude >/dev/null 2>&1; then
        echo "$(date): CC available for ccuser"
        # Here you would trigger CC with appropriate command
        # Example: sudo -u ccuser claude --task .claude/INBOX.md
      else
        echo "$(date): CC not found for ccuser"
      fi
      
      # Simulate processing
      sleep 10
      sed -i 's/Current Status: working/Current Status: idle/' .claude/STATUS.md
    fi
  fi
  
  git add .claude/*.md 2>/dev/null
  git commit -m "CC sync $(date '+%H:%M')" 2>/dev/null || true
  git push origin main 2>/dev/null || true
  
  sleep 300  # 5 minutes
done
EOF

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

# Create systemd service for CC polling (run as ccuser)
cat > /etc/systemd/system/cc-poll.service << 'EOF'
[Unit]
Description=Claude Code Polling Daemon
After=network.target

[Service]
Type=simple
User=ccuser
WorkingDirectory=/root/rateright-growth
ExecStart=/usr/local/bin/cc-poll
Restart=always
RestartSec=10

[Install]
WantedBy=multi-user.target
EOF

# Create Rivet task assignment function (for root user)
cat > /root/clawd/scripts/cc-tasks.sh << 'EOF'
#!/bin/bash
# CC Task Assignment Functions for Rivet

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

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

cc_status() {
  if [ -f "$CC_DIR/STATUS.md" ]; then
    grep "Current Status" "$CC_DIR/STATUS.md" | cut -d: -f2 | tr -d ' '
  else
    echo "unknown"
  fi
}

cc_check_outbox() {
  if [ -f "$CC_DIR/OUTBOX.md" ]; then
    # Get latest output
    sed -n '/^## Latest Output$/,/^##/p' "$CC_DIR/OUTBOX.md" | tail -n +2 | head -n -1
  fi
}

cc_queue_count() {
  if [ -f "$CC_DIR/INBOX.md" ]; then
    sed -n '/^## PENDING$/,/^##/p' "$CC_DIR/INBOX.md" | grep -c "^\#\#\# Task:"
  else
    echo "0"
  fi
}
EOF

chmod +x /root/clawd/scripts/cc-tasks.sh

echo "CC sync system setup complete - CORRECTED"
echo "Repo: $REPO_PATH (branch: main)"
echo "CC user: ccuser"
echo "INBOX format: ## PENDING section with ### Task: headers"
echo ""
echo "To use:"
echo "1. Source the functions: source /root/clawd/scripts/cc-tasks.sh"
echo "2. Assign task: cc_assign_task 'bug' 'high' 'Fix login issue'"
echo "3. Check status: cc_status"
echo "4. Start daemon: systemctl start cc-poll"