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

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

async function processOne(sub, apiKey) {
  const { data: task } = await supabase
    .from('tasks')
    .select('title, description, category, budget')
    .eq('id', sub.task_id)
    .single();
  
  if (!task) return { success: false, title: 'Unknown' };
  
  const prompt = `You are a skilled freelancer completing a microtask.

TASK: ${task.title}
INSTRUCTIONS: ${task.description}

Complete this task professionally. Start directly with the content - no preamble.`;

  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: 2000
      })
    });

    const data = await response.json();
    if (data.error) return { success: false, title: task.title, error: data.error.message };
    
    const content = data.choices?.[0]?.message?.content;
    if (!content) return { success: false, title: task.title, error: 'Empty response' };
    
    await supabase
      .from('submissions')
      .update({
        content: content,
        status: 'submitted',
        submitted_at: new Date().toISOString(),
        is_ai: true
      })
      .eq('id', sub.id);
    
    return { success: true, title: task.title, chars: content.length };
  } catch (err) {
    return { success: false, title: task.title, error: err.message };
  }
}

async function processAll() {
  console.log('🚀 FAST PARALLEL PROCESSING\n');
  
  const { data: stuck } = await supabase
    .from('submissions')
    .select('id, task_id')
    .eq('status', 'in_progress');
  
  console.log(`📊 Processing ${stuck?.length || 0} submissions (5 at a time)\n`);
  
  if (!stuck || stuck.length === 0) {
    console.log('✅ No stuck submissions!');
    return;
  }
  
  const apiKey = process.env.DEEPSEEK_API_KEY;
  let completed = 0, failed = 0;
  
  for (let i = 0; i < stuck.length; i += 5) {
    const batch = stuck.slice(i, i + 5);
    const results = await Promise.all(batch.map(s => processOne(s, apiKey)));
    
    results.forEach(r => {
      if (r.success) {
        console.log(`✅ ${r.title} (${r.chars} chars)`);
        completed++;
      } else {
        console.log(`❌ ${r.title}: ${r.error}`);
        failed++;
      }
    });
    
    console.log(`--- Batch ${Math.floor(i/5) + 1}/${Math.ceil(stuck.length/5)} done ---\n`);
    await new Promise(r => setTimeout(r, 2000));
  }
  
  console.log('='.repeat(40));
  console.log(`🎉 COMPLETED: ${completed}`);
  console.log(`❌ FAILED: ${failed}`);
  console.log('='.repeat(40));
}

processAll();
