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

const CELO_RPC = 'https://forno.celo.org';
const IDENTITY_REGISTRY = '0x8004A169FB4a3325136EB29fA0ceB6D2e539a432';
const AGENT_ID = 17;
const NEW_URI = 'ipfs://QmZQZ9uo1nCf8C8VN2dosebopoGaCjHhxU33Ye65RMy6iF';

const ABI = [
  'function setAgentURI(uint256 agentId, string uri)',
  'function tokenURI(uint256 tokenId) view returns (string)',
  'function ownerOf(uint256 tokenId) view returns (address)'
];

async function main() {
  const privateKey = process.env.PRIVATE_KEY;
  const provider = new ethers.JsonRpcProvider(CELO_RPC);
  const wallet = new ethers.Wallet(privateKey, provider);
  const contract = new ethers.Contract(IDENTITY_REGISTRY, ABI, wallet);

  console.log('Wallet:', wallet.address);
  const owner = await contract.ownerOf(AGENT_ID);
  console.log('Agent owner:', owner);

  if (owner.toLowerCase() !== wallet.address.toLowerCase()) {
    console.error('ERROR: Wrong wallet — not the owner of Agent #17');
    process.exit(1);
  }

  console.log('Setting URI to:', NEW_URI);
  const tx = await contract.setAgentURI(AGENT_ID, NEW_URI);
  console.log('TX sent:', tx.hash);
  await tx.wait();
  console.log('✅ URI updated on-chain!');

  const uri = await contract.tokenURI(AGENT_ID);
  console.log('New tokenURI:', uri);
}

main().catch(console.error);
