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 TOKEN_ID = 17;

// Try the full updateAgent ABI
const abi = [
  'function updateAgent(uint256 agentId, string calldata metadataURI, bytes32[] calldata serviceHashes) external',
  'function setTokenURI(uint256 tokenId, string calldata uri) external',
  'function tokenURI(uint256 tokenId) view returns (string)'
];

async function run() {
  const contract = new ethers.Contract(REGISTRY, abi, signer);
  
  const uri = 'ipfs://Qmb6ba8e9925919d71379cfd1b807d34342a78d35decb9';
  
  // Try updateAgent
  try {
    console.log('Trying updateAgent...');
    const tx = await contract.updateAgent(TOKEN_ID, uri, []);
    console.log('TX:', tx.hash);
    const r = await tx.wait();
    console.log('✅ Updated! Block:', r.blockNumber);
    return;
  } catch(e) { console.log('updateAgent failed:', e.message.substring(0, 150)); }

  // Try setTokenURI
  try {
    console.log('Trying setTokenURI...');
    const tx = await contract.setTokenURI(TOKEN_ID, uri);
    console.log('TX:', tx.hash);
    const r = await tx.wait();
    console.log('✅ Updated! Block:', r.blockNumber);
    return;
  } catch(e) { console.log('setTokenURI failed:', e.message.substring(0, 150)); }

  // Get the contract ABI from chain to find the right method
  console.log('\nChecking current tokenURI...');
  const current = await contract.tokenURI(TOKEN_ID);
  console.log('Current:', current);
}

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