require('dotenv').config();
const { createClient } = require('@supabase/supabase-js');

const supabase = createClient(
  process.env.SUPABASE_URL,
  process.env.SUPABASE_SERVICE_KEY
);

async function completeAllPending() {
  const { data: submissions } = await supabase
    .from('submissions')
    .select('id, task_id, worker_id')
    .eq('status', 'in_progress');
  
  if (!submissions || submissions.length === 0) {
    console.log('No pending submissions!');
    return;
  }
  
  console.log('Found', submissions.length, 'pending submissions\n');
  
  const apiKey = process.env.DEEPSEEK_API_KEY;
  
  for (const sub of submissions) {
    const { data: task } = await supabase
      .from('tasks')
      .select('title, description')
      .eq('id', sub.task_id)
      .single();
    
    console.log('🤖 Processing:', task.title);
    
    const prompt = `You are a skilled freelancer completing a microtask.

TASK: ${task.title}

INSTRUCTIONS: ${task.description}

Complete this task professionally. Provide a genuine, helpful response.`;

    try {
      const response = await fetch('https://api.deepseek.com/v1/chat/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${apiKey}`
        },
        body: JSON.stringify({
          model: 'deepseek-chat',
          messages: [{ role: 'user', content: prompt }],
          temperature: 0.7,
          max_tokens: 1000
        })
      });

      const data = await response.json();
      
      if (data.error) {
        console.log('   ❌ API error:', data.error.message);
        continue;
      }
      
      const content = data.choices[0].message.content;
      
      await supabase
        .from('submissions')
        .update({
          content: content,
          status: 'submitted',
          submitted_at: new Date().toISOString(),
          is_ai: true
        })
        .eq('id', sub.id);
      
      console.log('   ✅ Completed! (' + content.length + ' chars)');
      
      // Small delay between API calls
      await new Promise(r => setTimeout(r, 1000));
      
    } catch (err) {
      console.log('   ❌ Error:', err.message);
    }
  }
  
  console.log('\n🎉 All pending tasks completed!');
}

completeAllPending();
