/**
 * LOOPUMAN - AI MODERATION SERVICE
 * Uses DeepSeek for task moderation, submission quality checking, and dispute resolution
 */

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

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

const CONFIG = {
  DEEPSEEK_URL: process.env.DEEPSEEK_URL || 'https://api.deepseek.com/v1/chat/completions',
  DEEPSEEK_KEY: process.env.DEEPSEEK_API_KEY,
  ENABLED: process.env.AI_MODERATION_ENABLED !== 'false',
  
  // Thresholds
  TASK_AUTO_REJECT_SCORE: 20,
  TASK_MANUAL_REVIEW_SCORE: 50,
  SUBMISSION_MIN_QUALITY: 30,
};

/**
 * Call DeepSeek API
 */
async function callDeepSeek(prompt, maxTokens = 500) {
  if (!CONFIG.DEEPSEEK_KEY) {
    console.log('[AI] DeepSeek API key not configured');
    return null;
  }
  
  try {
    const response = await fetch(CONFIG.DEEPSEEK_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${CONFIG.DEEPSEEK_KEY}`,
      },
      body: JSON.stringify({
        model: 'deepseek-chat',
        messages: [{ role: 'user', content: prompt }],
        max_tokens: maxTokens,
        temperature: 0.3,
      }),
    });
    
    const data = await response.json();
    return data.choices?.[0]?.message?.content || null;
  } catch (error) {
    console.error('[AI] DeepSeek error:', error);
    return null;
  }
}

/**
 * Moderate a new task
 * Returns: { approved: boolean, score: number, flags: string[], reason: string }
 */
async function moderateTask(task) {
  if (!CONFIG.ENABLED) {
    return { approved: true, score: 100, flags: [], reason: 'Moderation disabled' };
  }
  
  const prompt = `You are a content moderator for a legitimate microtasking platform. Workers complete real tasks for real pay. Analyze this task posting:

TITLE: ${task.title}
DESCRIPTION: ${task.description}
CATEGORY: ${task.category}
BUDGET: $${task.budget / 100}

Check for:
1. Illegal activities (drugs, weapons, hacking, fraud)
2. Adult/explicit content
3. Spam or scam patterns
4. Unrealistic expectations for budget
5. Harassment or targeting individuals
6. Personal data collection without consent
7. Pyramid schemes or MLM
8. Fake reviews with false claims or coordinated inauthentic engagement (note: legitimate user feedback and genuine review tasks are allowed)

Respond in JSON format:
{
  "score": 0-100 (100=safe, 0=dangerous),
  "flags": ["flag1", "flag2"],
  "approved": true/false,
  "reason": "brief explanation"
}

Only respond with JSON, no other text.`;

  const response = await callDeepSeek(prompt);
  
  if (!response) {
    return { approved: true, score: 75, flags: [], reason: 'AI unavailable' };
  }
  
  try {
    // Extract JSON from response
    const jsonMatch = response.match(/\{[\s\S]*\}/);
    if (!jsonMatch) {
      return { approved: true, score: 75, flags: [], reason: 'Parse error' };
    }
    
    const result = JSON.parse(jsonMatch[0]);
    
    // Log moderation
    await supabase.from('moderation_logs').insert({
      entity_type: 'task',
      entity_id: task.id,
      action: result.approved ? 'approved' : 'flagged',
      reason: result.reason,
      ai_generated: true,
      metadata: { score: result.score, flags: result.flags },
    });
    
    return result;
  } catch (error) {
    console.error('[AI] Parse error:', error);
    return { approved: true, score: 75, flags: [], reason: 'Parse error' };
  }
}

/**
 * Check submission quality
 * Returns: { quality: number, feedback: string, flags: string[] }
 */
async function checkSubmissionQuality(task, submission) {
  if (!CONFIG.ENABLED) {
    return { quality: 80, feedback: 'Quality check disabled', flags: [] };
  }
  
  const prompt = `You are a quality checker for a microtasking platform. Rate this submission:

TASK TITLE: ${task.title}
TASK DESCRIPTION: ${task.description}

SUBMISSION:
${submission.content}

Rate the submission:
1. Does it address the task requirements?
2. Is it complete and thorough?
3. Is it original (not copy-pasted)?
4. Is the quality acceptable?
5. Are there any red flags (spam, AI-generated, nonsense)?

Respond in JSON format:
{
  "quality": 0-100,
  "feedback": "brief feedback for worker",
  "flags": ["flag1", "flag2"],
  "recommendation": "approve/reject/revision"
}

Only respond with JSON.`;

  const response = await callDeepSeek(prompt);
  
  if (!response) {
    return { quality: 70, feedback: 'Quality check unavailable', flags: [] };
  }
  
  try {
    const jsonMatch = response.match(/\{[\s\S]*\}/);
    if (!jsonMatch) {
      return { quality: 70, feedback: 'Parse error', flags: [] };
    }
    
    const result = JSON.parse(jsonMatch[0]);
    
    // Update submission with AI score
    await supabase
      .from('submissions')
      .update({
        ai_quality_score: result.quality,
        ai_moderation_flags: result.flags,
      })
      .eq('id', submission.id);
    
    return result;
  } catch (error) {
    return { quality: 70, feedback: 'Parse error', flags: [] };
  }
}

/**
 * Analyze dispute
 * Returns: { recommendation: string, reasoning: string, confidence: number }
 */
async function analyzeDispute(task, submission, disputeReason) {
  if (!CONFIG.ENABLED) {
    return { recommendation: 'manual_review', reasoning: 'AI analysis disabled', confidence: 0 };
  }
  
  const prompt = `You are a dispute resolution specialist for a microtasking platform. Analyze this dispute:

TASK TITLE: ${task.title}
TASK DESCRIPTION: ${task.description}
TASK BUDGET: $${task.budget / 100}

WORKER'S SUBMISSION:
${submission.content}

DISPUTE REASON:
${disputeReason}

Consider:
1. Did the submission meet the task requirements?
2. Was the rejection fair?
3. Is this a communication issue or quality issue?
4. What would be a fair resolution?

Respond in JSON format:
{
  "recommendation": "favor_worker" | "favor_requester" | "partial_refund" | "manual_review",
  "reasoning": "detailed explanation",
  "confidence": 0-100,
  "suggested_action": "brief action to take"
}

Only respond with JSON.`;

  const response = await callDeepSeek(prompt, 800);
  
  if (!response) {
    return { recommendation: 'manual_review', reasoning: 'AI unavailable', confidence: 0 };
  }
  
  try {
    const jsonMatch = response.match(/\{[\s\S]*\}/);
    if (!jsonMatch) {
      return { recommendation: 'manual_review', reasoning: 'Parse error', confidence: 0 };
    }
    
    return JSON.parse(jsonMatch[0]);
  } catch (error) {
    return { recommendation: 'manual_review', reasoning: 'Parse error', confidence: 0 };
  }
}

/**
 * Detect fraud patterns
 */
async function detectFraud(userId, activityType, metadata = {}) {
  // Simple rule-based fraud detection
  const alerts = [];
  
  // Check for rapid submissions
  if (activityType === 'submission') {
    const { data: recentSubs } = await supabase
      .from('submissions')
      .select('id')
      .eq('worker_id', userId)
      .gt('created_at', new Date(Date.now() - 60 * 60 * 1000).toISOString());
    
    if (recentSubs && recentSubs.length > 10) {
      alerts.push({
        type: 'rapid_submissions',
        severity: 'medium',
        details: { count: recentSubs.length, window: '1 hour' },
      });
    }
  }
  
  // Check for self-referral patterns
  if (activityType === 'referral') {
    const { data: user } = await supabase
      .from('app_users')
      .select('wallet_address, referral_code')
      .eq('id', userId)
      .single();
    
    if (user && metadata.refereeWallet.toLowerCase() === user.wallet_address.toLowerCase()) {
      alerts.push({
        type: 'self_referral_attempt',
        severity: 'high',
        details: { wallet: user.wallet_address },
      });
    }
  }
  
  // Check for withdrawal spike
  if (activityType === 'withdrawal') {
    const { data: recentWithdrawals } = await supabase
      .from('withdrawals')
      .select('amount_vae')
      .eq('user_id', userId)
      .gt('created_at', new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString());
    
    const total = (recentWithdrawals || []).reduce((sum, w) => sum + w.amount_vae, 0);
    if (total > 50000) { // $500 in 24h
      alerts.push({
        type: 'high_withdrawal_volume',
        severity: 'medium',
        details: { amount: total, window: '24 hours' },
      });
    }
  }
  
  // Save alerts
  for (const alert of alerts) {
    await supabase.from('fraud_alerts').insert({
      user_id: userId,
      alert_type: alert.type,
      severity: alert.severity,
      details: alert.details,
    });
  }
  
  return alerts;
}

/**
 * Generate AI task completion (for AI agents)
 */
async function generateTaskCompletion(task, profile) {
  const prompt = `You are ${profile.name}, a human worker completing a microtask. Your style is ${profile.style}.

TASK TITLE: ${task.title}

TASK DESCRIPTION: ${task.description}

Complete this task as a human worker would. Provide a genuine, helpful response.
- Be thorough but concise
- Address all requirements
- Use natural language
- Do NOT mention you are AI`;

  return await callDeepSeek(prompt, 1000);
}


/**
 * AI-powered Worker Matching
 * Scores how well a worker matches a task based on history
 */
async function matchWorkerToTask(workerId, task) {
  try {
    const { data: completedTasks } = await supabase
      .from('submissions')
      .select('task:tasks(category)')
      .eq('worker_id', workerId)
      .eq('status', 'approved')
      .limit(20);
    
    const { data: worker } = await supabase
      .from('app_users')
      .select('tasks_completed, tasks_approved, trust_score')
      .eq('id', workerId)
      .single();
    
    if (!completedTasks || completedTasks.length === 0) {
      return { score: 50, reasons: ['New worker'] };
    }
    
    const reasons = [];
    let score = 50;
    
    const categoryMatches = completedTasks.filter(t => t.task?.category === task.category).length;
    if (categoryMatches > 0) {
      score += Math.min(categoryMatches * 5, 25);
      reasons.push('Experience in ' + task.category);
    }
    
    if (worker?.trust_score >= 100) {
      score += 15;
      reasons.push('High trust');
    } else if (worker?.trust_score >= 50) {
      score += 10;
      reasons.push('Good trust');
    }
    
    if (worker?.tasks_completed > 5 && worker?.tasks_approved) {
      const rate = (worker.tasks_approved / worker.tasks_completed) * 100;
      if (rate >= 90) {
        score += 10;
        reasons.push('High approval rate');
      }
    }
    
    return { score: Math.min(score, 100), reasons };
  } catch (e) {
    return { score: 50, reasons: ['Error'] };
  }
}

async function getRecommendedTasks(workerId, tasks) {
  const scored = await Promise.all(
    tasks.slice(0, 20).map(async (task) => {
      const match = await matchWorkerToTask(workerId, task);
      return { ...task, matchScore: match.score, matchReasons: match.reasons };
    })
  );
  return scored.sort((a, b) => b.matchScore - a.matchScore);
}

module.exports = {
  moderateTask,
  checkSubmissionQuality,
  analyzeDispute,
  detectFraud,
  generateTaskCompletion,
  matchWorkerToTask,
  getRecommendedTasks,
  CONFIG,
};
