/**
 * ═══════════════════════════════════════════════════════════════════════════════
 * LOOPUMAN ON-CHAIN REPUTATION SERVICE
 * 13th January 2026
 * ═══════════════════════════════════════════════════════════════════════════════
 * 
 * Records worker reputation milestones on Celo blockchain.
 * 
 * HOW IT WORKS:
 * - No smart contract needed
 * - Uses transaction DATA field to store reputation hash
 * - Sends 0 CELO to worker's wallet with data attached
 * - Permanent, verifiable proof on CeloScan
 * - Cost: ~$0.001 per attestation
 * 
 * MILESTONES:
 * | Tasks | Badge        | Emoji |
 * |-------|--------------|-------|
 * | 10    | Rising Star  | ⭐    |
 * | 25    | Reliable     | 🌟    |
 * | 50    | Trusted      | ✨    |
 * | 100   | Expert       | 💫    |
 * | 250   | Elite        | 🏆    |
 * | 500   | Master       | 👑    |
 * | 1000  | Legendary    | 🌈    |
 * 
 * ═══════════════════════════════════════════════════════════════════════════════
 */

'use strict';

const { ethers } = require('ethers');
const crypto = require('crypto');
const { createClient } = require('@supabase/supabase-js');

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

// ═══════════════════════════════════════════════════════════════════════════════
// CONFIGURATION
// ═══════════════════════════════════════════════════════════════════════════════

const CONFIG = {
  // Celo RPC
  RPC_URL: process.env.CELO_RPC_URL || 'https://forno.celo.org',
  
  // Platform wallet (holds CELO for gas)
  PLATFORM_WALLET_KEY: process.env.CELO_PRIVATE_KEY,
  PLATFORM_WALLET_ADDRESS: process.env.CELO_WALLET_ADDRESS || '0x9F52C166c90567B7F9906c6319ef90aF4F516856',
  
  // Enable/disable attestations
  ENABLED: process.env.REPUTATION_ENABLED === 'true',
  
  // Milestones
  MILESTONES: [
    { tasks: 10, badge: 'Rising Star', emoji: '⭐' },
    { tasks: 25, badge: 'Reliable', emoji: '🌟' },
    { tasks: 50, badge: 'Trusted', emoji: '✨' },
    { tasks: 100, badge: 'Expert', emoji: '💫' },
    { tasks: 250, badge: 'Elite', emoji: '🏆' },
    { tasks: 500, badge: 'Master', emoji: '👑' },
    { tasks: 1000, badge: 'Legendary', emoji: '🌈' }
  ],
  
  // CeloScan URL
  CELOSCAN_URL: 'https://celoscan.io/tx/'
};

// ═══════════════════════════════════════════════════════════════════════════════
// MILESTONE DETECTION
// ═══════════════════════════════════════════════════════════════════════════════

/**
 * Get milestone for task count
 */
function getMilestoneForTasks(taskCount) {
  let milestone = null;
  
  for (const m of CONFIG.MILESTONES) {
    if (taskCount >= m.tasks) {
      milestone = m;
    }
  }
  
  return milestone;
}

/**
 * Get next milestone
 */
function getNextMilestone(taskCount) {
  for (const m of CONFIG.MILESTONES) {
    if (taskCount < m.tasks) {
      return m;
    }
  }
  return null;
}

/**
 * Check if user just reached a new milestone
 */
function checkNewMilestone(previousTasks, currentTasks) {
  for (const m of CONFIG.MILESTONES) {
    if (previousTasks < m.tasks && currentTasks >= m.tasks) {
      return m;
    }
  }
  return null;
}

// ═══════════════════════════════════════════════════════════════════════════════
// ON-CHAIN ATTESTATION
// ═══════════════════════════════════════════════════════════════════════════════

/**
 * Create reputation data hash
 */
function createReputationHash(userId, milestone, stats) {
  const data = {
    platform: 'loopuman',
    version: '1.0',
    userId,
    milestone: milestone.badge,
    tasksCompleted: stats.tasks_completed,
    successRate: stats.success_rate,
    averageRating: stats.average_rating,
    timestamp: new Date().toISOString()
  };
  
  const json = JSON.stringify(data);
  const hash = crypto.createHash('sha256').update(json).digest('hex');
  
  return { data, hash };
}

/**
 * Send attestation transaction to worker's wallet
 */
async function sendAttestation(workerWallet, dataHash) {
  if (!CONFIG.ENABLED) {
    console.log('Reputation attestations disabled');
    return { success: false, error: 'Disabled' };
  }
  
  if (!CONFIG.PLATFORM_WALLET_KEY) {
    console.error('No platform wallet key configured');
    return { success: false, error: 'No wallet key' };
  }
  
  try {
    const provider = new ethers.JsonRpcProvider(CONFIG.RPC_URL);
    const wallet = new ethers.Wallet(CONFIG.PLATFORM_WALLET_KEY, provider);
    
    // Prepare transaction data (0x + hash)
    const txData = '0x' + dataHash;
    
    // Send 0 CELO with data
    const tx = await wallet.sendTransaction({
      to: workerWallet,
      value: 0,
      data: txData
    });
    
    console.log(`📜 Attestation TX sent: ${tx.hash}`);
    
    // Wait for confirmation
    const receipt = await tx.wait();
    
    console.log(`✅ Attestation confirmed in block ${receipt.blockNumber}`);
    
    return {
      success: true,
      txHash: tx.hash,
      blockNumber: receipt.blockNumber
    };
    
  } catch (error) {
    console.error('Attestation failed:', error.message);
    return { success: false, error: error.message };
  }
}

// ═══════════════════════════════════════════════════════════════════════════════
// MAIN FUNCTIONS
// ═══════════════════════════════════════════════════════════════════════════════

/**
 * Check and attest milestone if reached
 * Call this after each task completion
 */
async function checkAndAttestMilestone(userId) {
  // Get user stats
  const { data: user } = await supabase
    .from('app_users')
    .select('tasks_completed, success_rate, average_rating, celo_wallet_address')
    .eq('id', userId)
    .single();
  
  if (!user) return { newMilestone: false };
  
  // Check which milestone they've reached
  const currentMilestone = getMilestoneForTasks(user.tasks_completed);
  if (!currentMilestone) return { newMilestone: false };
  
  // Check if already attested
  const { data: existing } = await supabase
    .from('reputation_attestations')
    .select('id, status')
    .eq('user_id', userId)
    .eq('milestone_badge', currentMilestone.badge)
    .single();
  
  if (existing) {
    // Already attested or pending
    return { newMilestone: false, existingAttestation: existing };
  }
  
  // New milestone reached!
  console.log(`🎉 User ${userId} reached ${currentMilestone.badge}!`);
  
  // Create reputation hash
  const { data: repData, hash: dataHash } = createReputationHash(userId, currentMilestone, user);
  
  // Check if user has wallet
  if (!user.celo_wallet_address) {
    // Record as pending wallet
    await supabase
      .from('reputation_attestations')
      .insert({
        user_id: userId,
        milestone_badge: currentMilestone.badge,
        milestone_tasks: currentMilestone.tasks,
        data_hash: dataHash,
        reputation_snapshot: repData,
        status: 'pending_wallet'
      });
    
    return {
      newMilestone: true,
      milestone: currentMilestone,
      needsWallet: true,
      notification: {
        title: `${currentMilestone.emoji} ${currentMilestone.badge}!`,
        message: `Congratulations! You've reached ${currentMilestone.badge} status!\n\n` +
                 `Connect your Celo wallet to receive your on-chain attestation.`
      }
    };
  }
  
  // Send on-chain attestation
  const txResult = await sendAttestation(user.celo_wallet_address, dataHash);
  
  if (txResult.success) {
    // Record successful attestation
    await supabase
      .from('reputation_attestations')
      .insert({
        user_id: userId,
        worker_wallet: user.celo_wallet_address,
        milestone_badge: currentMilestone.badge,
        milestone_tasks: currentMilestone.tasks,
        tx_hash: txResult.txHash,
        block_number: txResult.blockNumber,
        data_hash: dataHash,
        reputation_snapshot: repData,
        status: 'confirmed',
        confirmed_at: new Date().toISOString()
      });
    
    return {
      newMilestone: true,
      milestone: currentMilestone,
      txHash: txResult.txHash,
      celoscanUrl: CONFIG.CELOSCAN_URL + txResult.txHash,
      notification: {
        title: `${currentMilestone.emoji} ${currentMilestone.badge}!`,
        message: `Congratulations! You've reached ${currentMilestone.badge} status!\n\n` +
                 `🔗 Your achievement is now recorded on the Celo blockchain!\n` +
                 `View proof: ${CONFIG.CELOSCAN_URL + txResult.txHash}`
      }
    };
  } else {
    // Record failed attempt
    await supabase
      .from('reputation_attestations')
      .insert({
        user_id: userId,
        worker_wallet: user.celo_wallet_address,
        milestone_badge: currentMilestone.badge,
        milestone_tasks: currentMilestone.tasks,
        data_hash: dataHash,
        reputation_snapshot: repData,
        status: 'failed',
        error_message: txResult.error
      });
    
    return {
      newMilestone: true,
      milestone: currentMilestone,
      attestationFailed: true,
      notification: {
        title: `${currentMilestone.emoji} ${currentMilestone.badge}!`,
        message: `Congratulations! You've reached ${currentMilestone.badge} status!\n\n` +
                 `_On-chain attestation pending - we'll retry shortly._`
      }
    };
  }
}

/**
 * Retry pending attestations (call periodically)
 */
async function retryPendingAttestations() {
  const { data: pending } = await supabase
    .from('reputation_attestations')
    .select('*, app_users(celo_wallet_address)')
    .in('status', ['pending_wallet', 'failed'])
    .limit(10);
  
  if (!pending || pending.length === 0) return;
  
  for (const attestation of pending) {
    const wallet = attestation.app_users?.celo_wallet_address;
    
    if (!wallet) continue; // Still no wallet
    
    const txResult = await sendAttestation(wallet, attestation.data_hash);
    
    if (txResult.success) {
      await supabase
        .from('reputation_attestations')
        .update({
          worker_wallet: wallet,
          tx_hash: txResult.txHash,
          block_number: txResult.blockNumber,
          status: 'confirmed',
          confirmed_at: new Date().toISOString()
        })
        .eq('id', attestation.id);
    }
  }
}

// ═══════════════════════════════════════════════════════════════════════════════
// USER-FACING FUNCTIONS
// ═══════════════════════════════════════════════════════════════════════════════

/**
 * Get user's reputation profile
 */
async function getReputationProfile(userId) {
  // Get user stats
  const { data: user } = await supabase
    .from('app_users')
    .select('tasks_completed, success_rate, average_rating, celo_wallet_address, created_at')
    .eq('id', userId)
    .single();
  
  if (!user) return null;
  
  // Get attestations
  const { data: attestations } = await supabase
    .from('reputation_attestations')
    .select('*')
    .eq('user_id', userId)
    .eq('status', 'confirmed')
    .order('milestone_tasks', { ascending: true });
  
  // Current milestone
  const currentMilestone = getMilestoneForTasks(user.tasks_completed);
  const nextMilestone = getNextMilestone(user.tasks_completed);
  
  // Progress to next
  let progress = 100;
  if (nextMilestone) {
    const prevTasks = currentMilestone?.tasks || 0;
    progress = Math.round(((user.tasks_completed - prevTasks) / (nextMilestone.tasks - prevTasks)) * 100);
  }
  
  return {
    tasksCompleted: user.tasks_completed,
    successRate: user.success_rate,
    averageRating: user.average_rating,
    hasWallet: !!user.celo_wallet_address,
    memberSince: user.created_at,
    currentMilestone,
    nextMilestone,
    progressToNext: progress,
    attestations: attestations || [],
    badges: (attestations || []).map(a => ({
      badge: a.milestone_badge,
      txHash: a.tx_hash,
      celoscanUrl: CONFIG.CELOSCAN_URL + a.tx_hash,
      achievedAt: a.confirmed_at
    }))
  };
}

/**
 * Get reputation display text for Telegram
 */
async function getReputationDisplayText(userId) {
  const profile = await getReputationProfile(userId);
  
  if (!profile) {
    return '❌ Profile not found. Use /start to create your account.';
  }
  
  let text = `🏅 *YOUR REPUTATION*\n\n`;
  
  // Current status
  if (profile.currentMilestone) {
    text += `${profile.currentMilestone.emoji} *${profile.currentMilestone.badge}*\n\n`;
  } else {
    text += `🌱 *Explorer* (New)\n\n`;
  }
  
  // Stats
  text += `📊 *Stats*\n`;
  text += `├ Tasks: ${profile.tasksCompleted}\n`;
  text += `├ Success: ${profile.successRate}%\n`;
  text += `└ Rating: ${profile.averageRating}/5.0\n\n`;
  
  // Progress to next
  if (profile.nextMilestone) {
    text += `📈 *Next: ${profile.nextMilestone.emoji} ${profile.nextMilestone.badge}*\n`;
    text += `Progress: ${'█'.repeat(Math.floor(profile.progressToNext / 10))}${'░'.repeat(10 - Math.floor(profile.progressToNext / 10))} ${profile.progressToNext}%\n`;
    text += `(${profile.tasksCompleted}/${profile.nextMilestone.tasks} tasks)\n\n`;
  }
  
  // On-chain badges
  if (profile.badges.length > 0) {
    text += `🔗 *On-Chain Badges*\n`;
    profile.badges.forEach(b => {
      text += `• ${b.badge}\n`;
    });
    text += `\n_Verified on Celo blockchain_\n`;
  } else if (!profile.hasWallet) {
    text += `💡 Connect a Celo wallet to receive on-chain badges!\n`;
  }
  
  return text;
}

// ═══════════════════════════════════════════════════════════════════════════════
// EXPORTS
// ═══════════════════════════════════════════════════════════════════════════════

module.exports = {
  // Core functions
  checkAndAttestMilestone,
  retryPendingAttestations,
  sendAttestation,
  
  // Milestone helpers
  getMilestoneForTasks,
  getNextMilestone,
  checkNewMilestone,
  
  // User-facing
  getReputationProfile,
  getReputationDisplayText,
  
  // Config
  CONFIG
};
