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

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

const REGISTRY = '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432';
const AGENT_ID = 17;

const abi = [
  'function setAgentURI(uint256 agentId, string calldata newURI) external',
  'function tokenURI(uint256 tokenId) view returns (string)',
  'function setMetadata(uint256 agentId, string metadataKey, bytes metadataValue) external',
  'function getMetadata(uint256 agentId, string metadataKey) external view returns (bytes)'
];

async function run() {
  const contract = new ethers.Contract(REGISTRY, abi, signer);

  // 1. Check what's currently on-chain
  const currentURI = await contract.tokenURI(AGENT_ID);
  console.log('=== CURRENT ON-CHAIN URI ===');
  if (currentURI.startsWith('data:')) {
    const base64 = currentURI.split('base64,')[1];
    const decoded = JSON.parse(Buffer.from(base64, 'base64').toString());
    console.log(JSON.stringify(decoded, null, 2));
  } else {
    console.log(currentURI);
  }

  // 2. Check agent wallet metadata
  try {
    const walletMeta = await contract.getMetadata(AGENT_ID, 'agentWallet');
    console.log('\n=== AGENT WALLET METADATA ===');
    console.log('Raw:', walletMeta);
    console.log('Decoded:', ethers.AbiCoder.defaultAbiCoder().decode(['address'], walletMeta)[0]);
  } catch(e) { console.log('Wallet metadata:', e.message.substring(0, 100)); }

  // 3. If URI is still old, update again with more complete registration
  if (!currentURI.startsWith('data:')) {
    console.log('\n⚠️  URI still points to SelfClaw, updating...');
    const registration = buildRegistration();
    const dataURI = `data:application/json;base64,${Buffer.from(JSON.stringify(registration)).toString('base64')}`;
    const tx = await contract.setAgentURI(AGENT_ID, dataURI);
    await tx.wait();
    console.log('✅ Updated!');
  } else {
    console.log('\n✅ URI is already a data URI - 8004scan just needs to re-index');
  }
}

function buildRegistration() {
  return {
    "type": "https://eips.ethereum.org/EIPS/eip-8004#registration-v1",
    "name": "Loopuman",
    "description": "The Human Layer for AI — routes tasks to verified human workers worldwide via Telegram & WhatsApp. AI agents send requests, humans complete them, quality-checked results returned with 8-second cUSD payments on Celo. Services: data labeling, content moderation, surveys, translation, human verification oracles.",
    "image": "https://api.loopuman.com/logo.png",
    "services": [
      {"name": "A2A", "endpoint": "https://api.loopuman.com/api/v1/tasks/sync", "version": "0.3.0"},
      {"name": "MCP", "endpoint": "https://api.loopuman.com", "version": "2025-06-18"},
      {"name": "web", "endpoint": "https://loopuman.com"},
      {"name": "evm-wallet", "endpoint": "eip155:42220:0xeF4Acd50101C2afD14c2c213b30d8D8e9a91f0d2"}
    ],
    "x402Support": false,
    "active": true,
    "registrations": [
      {"agentId": 17, "agentRegistry": "eip155:42220:0x8004A169FB4a3325136EB29fA0ceB6D2e539a432"}
    ],
    "supportedTrust": ["reputation"]
  };
}

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