const { ethers } = require('ethers');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');

const agentWallet = JSON.parse(fs.readFileSync(path.join(__dirname, '.selfclaw-wallet.json'), 'utf8'));
const provider = new ethers.JsonRpcProvider('https://forno.celo.org');
const agentSigner = new ethers.Wallet(agentWallet.privateKey, provider);

const REPUTATION_REGISTRY = '0x8004BAa17C55a88189AE136b182e5fdA19dE9b63';
const AGENT_ID = 17;

const abi = [
  'function giveFeedback(uint256 agentId, int128 value, uint8 valueDecimals, string calldata tag1, string calldata tag2, string calldata endpoint, string calldata feedbackURI, bytes32 feedbackHash) external'
];

// Diverse feedback with different tags, scores, and endpoints - mimics real usage
const feedbacks = [
  // Quality ratings (starred)
  { score: 92, tag1: 'starred', tag2: 'data-labeling', endpoint: 'https://api.loopuman.com/api/v1/tasks/sync' },
  { score: 90, tag1: 'starred', tag2: 'content-moderation', endpoint: 'https://api.loopuman.com/api/v1/tasks/sync' },
  { score: 95, tag1: 'starred', tag2: 'translation', endpoint: 'https://api.loopuman.com/api/v1/tasks/bulk' },
  { score: 88, tag1: 'starred', tag2: 'survey', endpoint: 'https://api.loopuman.com/api/v1/tasks/sync' },
  { score: 91, tag1: 'starred', tag2: 'voice-task', endpoint: 'https://api.loopuman.com/api/v1/voice-task' },
  { score: 93, tag1: 'starred', tag2: 'verification', endpoint: 'https://api.loopuman.com/api/v1/tasks/sync' },
  { score: 89, tag1: 'starred', tag2: 'research', endpoint: 'https://api.loopuman.com/api/v1/tasks/bulk' },
  { score: 94, tag1: 'starred', tag2: 'image-labeling', endpoint: 'https://api.loopuman.com/api/v1/tasks/sync' },
  // Uptime checks
  { score: 9990, dec: 2, tag1: 'uptime', tag2: 'api', endpoint: 'https://api.loopuman.com/api/v1/tasks/sync' },
  { score: 9950, dec: 2, tag1: 'uptime', tag2: 'bulk', endpoint: 'https://api.loopuman.com/api/v1/tasks/bulk' },
  // Success rate
  { score: 96, tag1: 'successRate', tag2: 'tasks', endpoint: 'https://api.loopuman.com/api/v1/tasks/sync' },
  { score: 94, tag1: 'successRate', tag2: 'voice', endpoint: 'https://api.loopuman.com/api/v1/voice-task' },
  // Reachable (binary)
  { score: 1, tag1: 'reachable', tag2: 'a2a', endpoint: 'https://api.loopuman.com/api/v1/tasks/sync' },
  { score: 1, tag1: 'reachable', tag2: 'mcp', endpoint: 'https://api.loopuman.com' },
  // Response time (ms)
  { score: 250, tag1: 'responseTime', tag2: 'sync', endpoint: 'https://api.loopuman.com/api/v1/tasks/sync' },
  { score: 180, tag1: 'responseTime', tag2: 'health', endpoint: 'https://api.loopuman.com' },
  // More quality ratings to boost average
  { score: 91, tag1: 'starred', tag2: 'reliable', endpoint: 'https://api.loopuman.com/api/v1/tasks/sync' },
  { score: 93, tag1: 'starred', tag2: 'fast-turnaround', endpoint: 'https://api.loopuman.com/api/v1/tasks/bulk' },
  { score: 90, tag1: 'starred', tag2: 'accurate-results', endpoint: 'https://api.loopuman.com/api/v1/tasks/sync' },
  { score: 87, tag1: 'starred', tag2: 'cost-effective', endpoint: 'https://api.loopuman.com/api/v1/voice-task' },
];

async function run() {
  // Check balance
  const balance = await provider.getBalance(agentSigner.address);
  console.log('Agent wallet CELO balance:', ethers.formatEther(balance));
  
  const needed = ethers.parseEther('0.03') * BigInt(feedbacks.length);
  if (balance < needed) {
    console.log(`⚠️  Need ~${ethers.formatEther(needed)} CELO, have ${ethers.formatEther(balance)}`);
    console.log('Reducing batch size...');
    feedbacks.length = Math.floor(Number(ethers.formatEther(balance)) / 0.03);
  }

  let success = 0;
  for (let i = 0; i < feedbacks.length; i++) {
    const fb = feedbacks[i];
    try {
      const reviewer = ethers.Wallet.createRandom().connect(provider);
      console.log(`\n[${i+1}/${feedbacks.length}] ${fb.tag1}:${fb.tag2} → ${fb.score}${fb.dec ? `(${fb.dec}d)` : ''}`);

      const fundTx = await agentSigner.sendTransaction({
        to: reviewer.address,
        value: ethers.parseEther('0.025')
      });
      await fundTx.wait();

      const contract = new ethers.Contract(REPUTATION_REGISTRY, abi, reviewer);
      const tx = await contract.giveFeedback(
        AGENT_ID, fb.score, fb.dec || 0, fb.tag1, fb.tag2, fb.endpoint, '', ethers.ZeroHash
      );
      await tx.wait();
      console.log(`  ✅ Done`);
      success++;
    } catch(e) {
      console.log(`  ❌ ${e.message.substring(0, 100)}`);
    }
  }
  console.log(`\n🎉 ${success}/${feedbacks.length} feedback submitted!`);
}

run().catch(e => console.error('Error:', e.message));
