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;

// From the ERC-8004 spec: setAgentURI is the correct function
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);

  // Build a data URI with the full registration file including image
  const registration = {
    "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, 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"},
      {"name": "web", "endpoint": "https://loopuman.com"}
    ],
    "x402Support": false,
    "active": true,
    "registrations": [
      {"agentId": 17, "agentRegistry": "eip155:42220:0x8004A169FB4a3325136EB29fA0ceB6D2e539a432"}
    ],
    "supportedTrust": ["reputation"],
    "agentWallet": "0xeF4Acd50101C2afD14c2c213b30d8D8e9a91f0d2"
  };

  const json = JSON.stringify(registration);
  const base64 = Buffer.from(json).toString('base64');
  const dataURI = `data:application/json;base64,${base64}`;

  console.log('Current URI:');
  const current = await contract.tokenURI(AGENT_ID);
  console.log(current.substring(0, 80) + '...');

  console.log('\nUpdating to data URI with image + description...');
  try {
    const tx = await contract.setAgentURI(AGENT_ID, dataURI);
    console.log('TX:', tx.hash);
    const receipt = await tx.wait();
    console.log('✅ URI updated! Block:', receipt.blockNumber);
    
    // Verify
    const newURI = await contract.tokenURI(AGENT_ID);
    console.log('New URI starts with:', newURI.substring(0, 50));
  } catch(e) {
    console.log('❌ setAgentURI failed:', e.message.substring(0, 200));
  }
}

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