#!/bin/bash
# Executa um plano Ralph Wiggum usando Claude Code CLI
# Requer: claude (Claude Code CLI instalado), node

set -e

PLAN_FILE="${1:-plan.yaml}"

if [ ! -f "$PLAN_FILE" ]; then
  echo "Uso: $0 <plan.yaml>"
  echo ""
  echo "Exemplo:"
  echo "  rw-uc generate -t 'Criar CRUD de produtos' -o plan.yaml"
  echo "  rw-uc-run plan.yaml"
  exit 1
fi

# Verificar se claude está instalado
if ! command -v claude &> /dev/null; then
  echo "❌ Claude Code CLI não encontrado."
  echo ""
  echo "Instale com: npm install -g @anthropic-ai/claude-code"
  exit 1
fi

# Verificar se node está instalado
if ! command -v node &> /dev/null; then
  echo "❌ Node.js não encontrado."
  exit 1
fi

echo "🚀 Executando plano: $PLAN_FILE"
echo ""

# Usar Node.js para processar o YAML e executar tasks
node --input-type=module -e "
import { readFileSync, writeFileSync, unlinkSync } from 'fs';
import { parse } from 'yaml';
import { execSync, spawnSync } from 'child_process';
import * as readline from 'readline';

const planFile = '$PLAN_FILE';
const content = readFileSync(planFile, 'utf-8');
const plan = parse(content);

console.log('Feature:', plan.featureName);
console.log('Tasks:', plan.tasks.length);
console.log('');

const autoCommit = plan.config?.autoCommit ?? false;

for (let i = 0; i < plan.tasks.length; i++) {
  const task = plan.tasks[i];

  console.log('═'.repeat(60));
  console.log(\`[\${i + 1}/\${plan.tasks.length}] \${task.name}\`);
  console.log('═'.repeat(60));

  // Criar arquivo temporário com o prompt
  const tempFile = \`/tmp/ralph-task-\${task.id}.md\`;
  writeFileSync(tempFile, task.prompt);

  console.log('Executando com Claude Code...');
  console.log('');

  try {
    // Executar claude com o prompt
    const result = spawnSync('claude', ['--dangerously-skip-permissions'], {
      input: task.prompt,
      stdio: ['pipe', 'inherit', 'inherit'],
      encoding: 'utf-8',
      maxBuffer: 50 * 1024 * 1024
    });

    if (result.status === 0) {
      console.log('');
      console.log('✅ Task concluída:', task.id);

      // Commit automático se configurado
      if (autoCommit && task.commitMessage) {
        console.log('📝 Commit:', task.commitMessage);
        try {
          execSync(\`git add -A && git commit -m \"\${task.commitMessage}\"\`, {
            stdio: 'pipe'
          });
          console.log('✅ Commit realizado');
        } catch (e) {
          console.log('⚠️  Nada para commitar ou erro no commit');
        }
      }
    } else {
      throw new Error(\`Exit code: \${result.status}\`);
    }

  } catch (error) {
    console.error('');
    console.error('❌ Erro na task:', task.id);
    console.error(error.message);

    // Perguntar se continua
    const rl = readline.createInterface({
      input: process.stdin,
      output: process.stdout
    });

    const answer = await new Promise(resolve => {
      rl.question('Continuar com próxima task? (s/n) ', resolve);
    });
    rl.close();

    if (answer.toLowerCase() !== 's') {
      console.log('Execução interrompida.');
      process.exit(1);
    }
  }

  // Limpar arquivo temporário
  try { unlinkSync(tempFile); } catch {}

  console.log('');
}

console.log('🎉 Pipeline concluído!');
"
