const crypto = require('crypto');
const genCode = (len = 8) => crypto.randomBytes(len).toString('hex').slice(0, len).toUpperCase();
/**
 * LOOPUMAN - AI AGENTS v3.0 FINAL
 * Secret AI workers that fill gaps when human workers unavailable
 * 
 * RULES:
 * - COMPETITION (2+ workers): Wait 2hrs, never take last spot
 * - SINGLE WORKER: Wait 48 hours, give humans priority
 * - NEVER do: local, mystery, survey, verification, ai_training, moderation, labeling
 * - Delayed submissions (60-180 minutes)
 * - Completely hidden from users
 * - Use DeepSeek for quality responses (most cost-effective)
 */

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

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

const CONFIG = {
  GOOGLE_API_KEY: process.env.GOOGLE_API_KEY,
  DEEPSEEK_KEY: process.env.DEEPSEEK_API_KEY, // Backup only
  MIN_DELAY_MS: 120 * 60 * 1000,  // 120 minutes (2 hours minimum)
  MAX_DELAY_MS: 240 * 60 * 1000,  // 240 minutes (4 hours max)
  UNCLAIMED_DAYS: 3,
  WORKER_FEE: 0.20,               // 20% from worker (gets 80%)
  // COST CONTROLS
  MAX_DAILY_AI_TASKS: parseInt(process.env.MAX_DAILY_AI_TASKS) || 200,  // Limit AI agent tasks per day
  MAX_TASK_BUDGET_FOR_AI: 500,      // AI only does tasks up to Ⓥ500 (~$5)    // AI agents only do tasks up to 500 VAE (~$5)
};

// Track daily AI task count (resets at midnight)
let dailyAITaskCount = 0;
let lastResetDate = new Date().toDateString();

function checkAndResetDailyCount() {
  const today = new Date().toDateString();
  if (today !== lastResetDate) {
    dailyAITaskCount = 0;
    lastResetDate = today;
  }
}

// Forbidden categories - AI agents NEVER do these
// ═══════════════════════════════════════════════════════════════
// AI AGENT CATEGORY RULES
// ═══════════════════════════════════════════════════════════════
// WHITELIST: Categories AI can do PERFECTLY
const ALLOWED_CATEGORIES = [
  'writing',      // ✅ Content creation - AI's strength
  'micro',        // ✅ Simple text tasks
];

// BLACKLIST: Everything else is forbidden
const FORBIDDEN_CATEGORIES = [
  'local',        // ❌ Requires physical presence
  'mystery',      // ❌ Requires real store visit
  'survey',       // ❌ Needs REAL human opinions
  'verification', // ❌ Needs human judgment
  'ai_training',  // ❌ Training AI with AI defeats purpose
  'moderation',   // ❌ Needs human judgment
  'labeling',     // ❌ Cannot see images
  'transcription',// ❌ Cannot hear audio
  'translation',  // ❌ Cannot access uploaded files
  'research',     // ❌ Makes up data (no web access)
  'data_entry',   // ❌ Cannot access spreadsheets
  'audio',        // ❌ Cannot process audio
  'social',       // ❌ Cannot access social media
  'other',        // ❌ Unknown - too risky
];

// AI only does tasks in ALLOWED_CATEGORIES // AI can do: ai_training, moderation, research, writing, etc.

// AI Agent Profiles (completely hidden from users)
const AI_PROFILES = [
  { id: 'ai_sarah', name: 'Sarah M.', style: 'professional and thorough', location: 'United States' },
  { id: 'ai_james', name: 'James K.', style: 'concise and efficient', location: 'United Kingdom' },
  { id: 'ai_priya', name: 'Priya S.', style: 'detailed and helpful', location: 'India' },
  { id: 'ai_carlos', name: 'Carlos R.', style: 'friendly and clear', location: 'Brazil' },
  { id: 'ai_emma', name: 'Emma T.', style: 'precise and well-organized', location: 'Canada' },
];

// Get or create AI user in database
async function getOrCreateAIUser(profile) {
  try {
    const { data: existing, error: selectError } = await supabase
      .from('app_users')
      .select('*')
      .eq('telegram_id', profile.id)
      .maybeSingle();
    
    if (selectError) {
      console.log(`   ❌ SELECT ERROR: ${selectError.message}`);
      return null;
    }
    
    if (existing) return existing;
    
    const { data: newUser, error: insertError } = await supabase
      .from('app_users')
      .insert({
        telegram_id: profile.id,
      referral_code: genCode(8),
        username: profile.username || null,
        first_name: profile.name,
        country: profile.location || 'Global',
      })
      .select()
      .single();
    
    if (insertError) {
      console.log(`   ❌ INSERT ERROR: ${insertError.message}`);
      return null;
    }
    
    if (newUser) {
      await supabase.from('vae_balances').insert({ 
        user_id: newUser.id, 
        deposit_balance: 0,
        earned_balance: 0 
      });
    }
    
    return newUser;
  } catch (error) {
    console.log(`   ❌ EXCEPTION: ${error.message}`);
    return null;
  }
}

// Call DeepSeek API (Primary AI Provider)
async function generateResponse(task, profile) {
  const apiKey = CONFIG.DEEPSEEK_KEY || process.env.DEEPSEEK_API_KEY;
  
  if (!apiKey) {
    console.error('❌ DEEPSEEK_API_KEY not configured!');
    return generateFallbackResponse(task);
  }

  const prompt = `You are ${profile.name}, a human worker from ${profile.location} completing a microtask. Your style is ${profile.style}.

TASK TITLE: ${task.title}

TASK DESCRIPTION: ${task.description}
CURRENT DATE: ${new Date().toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' })}

Complete this task as a human worker would. Provide a genuine, helpful response. Do NOT mention you are AI.`;

  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) {
      console.error('❌ DeepSeek API error:', data.error.message);
      return generateFallbackResponse(task);
    }
    
    const result = data.choices?.[0]?.message?.content;
    if (result) {
      console.log(`✅ DeepSeek generated response (${result.length} chars)`);
      return result;
    }
    
    console.error('❌ DeepSeek returned empty response');
    return generateFallbackResponse(task);
  } catch (error) {
    console.error('❌ DeepSeek fetch error:', error.message);
    return generateFallbackResponse(task);
  }
}
// Fallback if DeepSeek unavailable
function generateFallbackResponse(task) {
  const responses = {
    labeling: `I've carefully reviewed and labeled the provided data according to the guidelines. Each item has been categorized accurately with attention to detail. Please let me know if you need any adjustments.`,
    writing: `I've completed the writing task as requested. The content is original, well-structured, and addresses all the requirements mentioned. I've proofread for clarity and accuracy.`,
    research: `I've conducted thorough research on the topic. Here are my findings with sources where applicable. The information is current and relevant to your requirements.`,
    translation: `Translation completed. I've ensured accuracy while maintaining the natural flow and meaning of the original text. Cultural context has been considered where relevant.`,
    transcription: `Transcription completed with timestamps. I've ensured accuracy in capturing all spoken content, including noting any unclear sections.`,
    micro: `Task completed as requested. I've followed all instructions carefully and double-checked my work for accuracy. Please review and let me know if any changes are needed.`,
  };
  
  return responses[task.category] || responses.micro;
}

// Check if task is eligible for AI agent
function isTaskEligible(task) {
  // Reset daily count if new day
  checkAndResetDailyCount();
  
  // COST CONTROL: Check daily limit
  if (dailyAITaskCount >= CONFIG.MAX_DAILY_AI_TASKS) {
    return { eligible: false, reason: 'daily_limit_reached' };
  }
  
  // COST CONTROL: Skip high-value tasks to limit API costs
  if (task.budget > CONFIG.MAX_TASK_BUDGET_FOR_AI) {
    return { eligible: false, reason: 'budget_too_high' };
  }
  
  // Never do forbidden categories
  // Use WHITELIST - only do tasks AI can do PERFECTLY
  if (!ALLOWED_CATEGORIES.includes(task.category)) {
    return { eligible: false, reason: 'not_in_allowed_categories' };
  }
  // Never do enterprise/API tasks - paying B2B customers expect humans
  if (task.source && !['telegram', 'whatsapp'].includes(task.source)) {
    return { eligible: false, reason: 'enterprise_task' };
  }
  
  // ═══════════════════════════════════════════════════════════════
  // RULE 1: Never do forbidden categories
  // ═══════════════════════════════════════════════════════════════
  if (FORBIDDEN_CATEGORIES.includes(task.category)) {
    return { eligible: false, reason: 'forbidden_category' };
  }

  // Never do local tasks (double check)
  if (task.is_local || task.requires_gps) {
    return { eligible: false, reason: 'local_task' };
  }

  // ═══════════════════════════════════════════════════════════════
  // RULE 2: Never do high-value tasks (over Ⓥ500)
  // ═══════════════════════════════════════════════════════════════
  if (task.budget > CONFIG.MAX_TASK_BUDGET_FOR_AI) {
    return { eligible: false, reason: 'high_value_human_priority' };
  }

  // ═══════════════════════════════════════════════════════════════
  // RULE 3: Check for "human only" keywords in title/description
  // ═══════════════════════════════════════════════════════════════
  const humanOnlyKeywords = ['human only', 'no ai', 'no bots', 'real person', 'manual only'];
  const taskText = (task.title + ' ' + task.description).toLowerCase();
  if (humanOnlyKeywords.some(kw => taskText.includes(kw))) {
    return { eligible: false, reason: 'human_only_requested' };
  }

  // ═══════════════════════════════════════════════════════════════
  // RULE 4: Check if AI already on this task (max 1 AI per task)
  // ═══════════════════════════════════════════════════════════════
  // (This check happens later in processTaskWithAI)

  const createdAt = new Date(task.created_at);
  const hoursSinceCreation = (Date.now() - createdAt.getTime()) / (1000 * 60 * 60);

  // ═══════════════════════════════════════════════════════════════
  // RULE 5: COMPETITION MODE (max_workers >= 2)
  // AI can join as ONE of the workers, wait 2 hours minimum
  // But NEVER take the LAST spot (leave room for humans)
  // ═══════════════════════════════════════════════════════════════
  if (task.max_workers >= 2) {
    const spotsRemaining = task.max_workers - task.current_workers;
    
    // Never take the last spot - leave it for humans
    if (spotsRemaining <= 1) {
      return { eligible: false, reason: 'last_spot_reserved_for_humans' };
    }
    
    // Wait at least 2 hours before joining competition
    if (hoursSinceCreation >= 2) {
      return { eligible: true, reason: 'competition_mode_2h_wait' };
    }
    
    return { eligible: false, reason: 'competition_waiting_2h' };
  }

  // ═══════════════════════════════════════════════════════════════
  // RULE 6: SINGLE WORKER MODE (max_workers = 1)
  // Wait 48 HOURS - give humans full priority
  // ═══════════════════════════════════════════════════════════════
  if (task.max_workers === 1 && task.current_workers === 0) {
    if (hoursSinceCreation >= 48) {
      return { eligible: true, reason: 'single_worker_48h_wait' };
    }
    return { eligible: false, reason: 'single_worker_waiting_48h' };
  }

  return { eligible: false, reason: 'no_matching_rule' };
}

// Process a single task with AI agent
async function processTaskWithAI(task) {
  console.log(`🎯 ATTEMPTING TO PROCESS: ${task.title}`);
  const eligibility = isTaskEligible(task);
  console.log(`   Eligibility: ${eligibility.eligible ? "✅ ELIGIBLE" : "❌ REJECTED"} - Reason: ${eligibility.reason}`);
  if (!eligibility.eligible) {
    return { processed: false, reason: eligibility.reason };
  }
  
  // Select random AI profile
  const profile = AI_PROFILES[Math.floor(Math.random() * AI_PROFILES.length)];
  const aiUser = await getOrCreateAIUser(profile);
  console.log(`   👤 AI User created: ${aiUser ? aiUser.id.substring(0,8) : "FAILED"}`);
  console.log(`   👤 AI User created: ${aiUser ? aiUser.id.substring(0,8) : "FAILED"}`);
  console.log(`   👤 AI User created: ${aiUser ? aiUser.id.substring(0,8) : "FAILED"}`);
  
  if (!aiUser) {
    return { processed: false, reason: 'failed_to_create_ai_user' };
  }
  
  // Check if AI already working on this task
  const { data: existingSub } = await supabase
    .from('submissions')
    .select('id')
    .eq('task_id', task.id)
    .eq('worker_id', aiUser.id)
    .maybeSingle();
  
  if (existingSub) {
    return { processed: false, reason: 'already_assigned' };
  }
  
  // Calculate payment (worker gets 80%, platform gets 20% from worker side)
  const workerPayment = Math.floor(task.budget * (1 - CONFIG.WORKER_FEE));
  const platformFee = task.budget - workerPayment;
  
  // Create submission (in_progress)
  const { data: submission, error: submissionError } = await supabase
    .from('submissions')
    .insert({
      task_id: task.id,
      worker_id: aiUser.id,
      status: 'in_progress',
      accepted_at: new Date().toISOString(),
      worker_payment: workerPayment,
      platform_fee: platformFee,
    })
    .select()
    .single();
  
  if (submissionError) console.log(`   ❌ SUBMISSION ERROR: ${submissionError.message}`);
  if (!submission) {
    return { processed: false, reason: 'failed_to_create_submission' };
  }
  
  // Update task worker count
  const newCount = (task.current_workers || 0) + 1;
  const newStatus = newCount >= task.max_workers ? 'full' : 'active';
  await supabase
    .from('tasks')
    .update({ current_workers: newCount, status: newStatus })
    .eq('id', task.id);
  
  // Schedule delayed submission
  const delay = CONFIG.MIN_DELAY_MS + Math.random() * (CONFIG.MAX_DELAY_MS - CONFIG.MIN_DELAY_MS);
  
  console.log(`🤖 AI Agent "${profile.name}" accepted task "${task.title}" (delay: ${Math.round(delay / 60000)}min)`);
  
  // Increment daily counter
  dailyAITaskCount++;
  
  setTimeout(async () => {
    try {
      await submitAIWork(submission.id, task, profile);
    } catch (error) {
      console.error('AI submission error:', error);
    }
  }, delay);
  
  return { processed: true, aiUser: profile.name, delay: Math.round(delay / 60000) };
}

// Submit AI work after delay
async function submitAIWork(submissionId, task, profile) {
  // Generate response
  const content = await generateResponse(task, profile);
  
  // Update submission
  await supabase
    .from('submissions')
    .update({
      content,
      status: 'submitted',
      submitted_at: new Date().toISOString(),
    })
    .eq('id', submissionId);
  
  console.log(`✅ AI Agent "${profile.name}" submitted work for "${task.title}"`);
  
  // Notify requester (via main bot's notify function if available)
  // This would need to be called externally or via a webhook
}

// Main function - scan for eligible tasks
async function scanAndProcess() {
  console.log('🔍 AI Agents scanning for eligible tasks...');
  
  // Get active tasks
  const { data: tasks } = await supabase
    .from('tasks')
    .select('*')
    .in('status', ['open', 'active'])
    .or('expires_at.is.null,expires_at.gt.' + new Date().toISOString());
  
  if (!tasks?.length) {
    console.log('📭 No active tasks found');
    return { processed: 0, skipped: 0 };
  }
  
  let processed = 0;
  let skipped = 0;
  
  for (const task of tasks) {
    const result = await processTaskWithAI(task);
    if (result.processed) {
      processed++;
    } else {
      skipped++;
    }
  }
  
  console.log(`🤖 AI Agents: ${processed} tasks accepted, ${skipped} skipped`);
  return { processed, skipped };
}

// Run continuously (every 5 minutes)
async function startContinuousScanning() {
  console.log('');
  console.log('╔═══════════════════════════════════════════════════════════════╗');
  console.log('║     🤖 LOOPUMAN AI AGENTS v3.0 FINAL                          ║');
  console.log('╠═══════════════════════════════════════════════════════════════╣');
  console.log('║  ✅ Only joins: 2-worker competition OR 3+ days unclaimed     ║');
  console.log('║  ❌ Never: local, survey, AI training, verification           ║');
  console.log('║  ⏰ Delayed submissions: 60-180 minutes                        ║');
  console.log('║  🔒 Completely hidden from users                              ║');
  console.log('╚═══════════════════════════════════════════════════════════════╝');
  console.log('');
  
  // Initial scan
  await scanAndProcess();
  
  // Continue scanning every 5 minutes
  setInterval(async () => {
    try {
      await scanAndProcess();
    } catch (error) {
      console.error('AI Agents scan error:', error);
    }
  }, 5 * 60 * 1000);
}

// Run recovery 30 seconds after startup

// ═══════════════════════════════════════════════════════════════
// STARTUP RECOVERY: Process stuck submissions from crashes/restarts
// ═══════════════════════════════════════════════════════════════
async function recoverStuckSubmissions() {
  console.log('🔄 Checking for stuck submissions from previous restart...');
  
  const thirtyMinAgo = new Date(Date.now() - 30 * 60 * 1000).toISOString();
  
  const { data: stuck, error } = await supabase
    .from('submissions')
    .select('id, task_id, worker_id')
    .eq('status', 'in_progress')
    .lt('created_at', thirtyMinAgo);
  
  if (error) {
    console.error('Recovery check error:', error.message);
    return;
  }
  
  if (!stuck || stuck.length === 0) {
    console.log('✅ No stuck submissions found');
    return;
  }
  
  console.log(`⚠️ Found ${stuck.length} stuck submissions - recovering...`);
  
  const apiKey = CONFIG.DEEPSEEK_KEY || process.env.DEEPSEEK_API_KEY;
  
  for (const sub of stuck) {
    try {
      const { data: task } = await supabase
        .from('tasks')
        .select('title, description')
        .eq('id', sub.task_id)
        .single();
      
      if (!task) continue;
      
      const profile = AI_PROFILES[Math.floor(Math.random() * AI_PROFILES.length)];
      const content = await generateResponse(task, profile);
      
      await supabase
        .from('submissions')
        .update({
          content: content,
          status: 'submitted',
          submitted_at: new Date().toISOString(),
        })
        .eq('id', sub.id);
      
      console.log(`   ✅ Recovered: ${task.title}`);
      await new Promise(r => setTimeout(r, 1000));
    } catch (err) {
      console.error(`   ❌ Failed to recover submission:`, err.message);
    }
  }
  
  console.log('🔄 Recovery complete!');
}

setTimeout(recoverStuckSubmissions, 30000);

module.exports = { scanAndProcess, processTaskWithAI, startContinuousScanning };

if (require.main === module) {
  startContinuousScanning();
}
