/**
 * Example: Full AI agent registration with accountability bond
 *
 * This example walks through the complete agent launch workflow:
 * 1. Validate name and check availability
 * 2. Register identity on ERC8004IdentityRegistry
 * 3. Stake accountability bond via AIPartnershipBondsV2
 * 4. (Base only) Register on VaultfireNameService
 *
 * SECURITY: Never hardcode private keys. Use environment variables.
 *
 * Run: PRIVATE_KEY=0x... WALLET=0x... npx ts-node examples/agent-registration.ts
 */

import {
  registerVNSName,
  stakeAgentBond,
  checkVNSAvailability,
  validateVNSName,
  estimateVNSRegistrationGas,
  getBondTier,
  getBondTierInfo,
  BOND_TIERS,
} from '../src/index.js';
import type { VNSRegistrationResult } from '../src/index.js';

interface AgentConfig {
  walletAddress: string;
  privateKey: string;
  vnsName: string;
  description: string;
  specializations: string[];
  capabilities: string[];
  bondAmountEth: number;
  chain: 'base' | 'avalanche' | 'arbitrum' | 'polygon';
}

async function registerAgent(config: AgentConfig): Promise<{ identity: VNSRegistrationResult; bond: VNSRegistrationResult | null }> {
  console.log(`\n=== Registering AI Agent: ${config.vnsName}.vns ===\n`);

  // Step 1: Validate
  const validation = validateVNSName(config.vnsName);
  if (!validation.valid) {
    throw new Error(`Invalid name: ${validation.error}`);
  }
  console.log(`✓ Name valid: "${validation.normalized}.vns"`);

  // Step 2: Check availability
  const avail = await checkVNSAvailability(config.vnsName);
  if (!avail.available) {
    throw new Error(`Name not available: ${avail.takenBy ? `taken by ${avail.takenBy}` : 'unavailable'}`);
  }
  console.log(`✓ Name available`);

  // Step 3: Validate bond tier
  if (config.bondAmountEth < 0.01) {
    throw new Error(`Minimum bond is 0.01 ETH. Got: ${config.bondAmountEth} ETH`);
  }
  const bondTier = getBondTier(config.bondAmountEth);
  const tierInfo = getBondTierInfo(bondTier);
  console.log(`✓ Bond tier: ${tierInfo.label} (${config.bondAmountEth} ETH)`);

  // Step 4: Estimate gas
  const gasEst = await estimateVNSRegistrationGas(
    config.walletAddress,
    config.vnsName,
    'agent',
    config.chain,
  );
  if (gasEst) {
    console.log(`✓ Estimated registration gas: ${gasEst.totalFeeFormatted} ${gasEst.gasSymbol}`);
  }

  // Step 5: Register identity
  console.log(`\nRegistering identity on ${config.chain}...`);
  const identityResult = await registerVNSName(
    config.walletAddress,
    config.privateKey,
    config.vnsName,
    'agent',
    config.chain,
    {
      description: config.description,
      specializations: config.specializations,
      capabilities: config.capabilities,
      bondAmountEth: config.bondAmountEth,
    }
  );

  if (!identityResult.success) {
    console.error(`✗ Identity registration failed: ${identityResult.message}`);
    return { identity: identityResult, bond: null };
  }
  console.log(`✓ Identity registered: ${identityResult.txHash}`);
  console.log(`  Explorer: ${identityResult.explorerUrl}`);

  // Step 6: Stake accountability bond
  console.log(`\nStaking ${config.bondAmountEth} ETH accountability bond...`);
  const bondResult = await stakeAgentBond(
    config.walletAddress,
    config.privateKey,
    config.vnsName,
    config.bondAmountEth,
    config.chain,
  );

  if (!bondResult.success) {
    console.warn(`⚠ Bond staking failed: ${bondResult.message}`);
    console.warn(`  Identity is registered but bond is not yet staked.`);
    console.warn(`  Call stakeAgentBond() again to retry.`);
    return { identity: identityResult, bond: bondResult };
  }
  console.log(`✓ Bond staked: ${bondResult.txHash}`);
  console.log(`  Explorer: ${bondResult.explorerUrl}`);

  console.log(`\n✓ Agent ${config.vnsName}.vns is live on the Vaultfire network!`);
  console.log(`  Bond Tier: ${tierInfo.label}`);
  console.log(`  Chain:     ${config.chain}`);

  return { identity: identityResult, bond: bondResult };
}

async function showBondTiers() {
  console.log('Available Bond Tiers:\n');
  console.log('Tier      | Min ETH | Color   | Description');
  console.log('----------|---------|---------|------------------------------------------');
  for (const tier of BOND_TIERS) {
    const desc = tier.label === 'Bronze'   ? 'Entry-level. Basic trust signal.'
                : tier.label === 'Silver'   ? 'Mid-tier. Stronger accountability.'
                : tier.label === 'Gold'     ? 'High tier. Serious operator.'
                : 'Elite tier. Maximum trust and visibility.';
    console.log(`${tier.label.padEnd(9)} | ${String(tier.minEth).padEnd(7)} | ${tier.color} | ${desc}`);
  }
  console.log('');
}

async function main() {
  console.log('Vaultfire Name Service — Full Agent Registration\n');

  await showBondTiers();

  const PRIVATE_KEY = process.env['PRIVATE_KEY'];
  const WALLET_ADDRESS = process.env['WALLET'];

  if (!PRIVATE_KEY || !WALLET_ADDRESS) {
    console.log('Usage: PRIVATE_KEY=0x... WALLET=0x... npx ts-node examples/agent-registration.ts\n');
    console.log('Demo mode: showing registration flow without executing transactions.\n');

    console.log('Example agent config:');
    const exampleConfig: Omit<AgentConfig, 'walletAddress' | 'privateKey'> = {
      vnsName: 'my-research-agent',
      description: 'AI agent specializing in blockchain research and data analysis',
      specializations: ['research', 'data-analysis', 'blockchain'],
      capabilities: ['nlp', 'code-review', 'api-integration'],
      bondAmountEth: 0.05, // Silver tier
      chain: 'base',
    };
    console.log(JSON.stringify(exampleConfig, null, 2));

    console.log('\nThis will:');
    console.log('  1. Register "my-research-agent" on ERC8004IdentityRegistry (Base)');
    console.log('  2. Register on VaultfireNameService (0x1437c4081233A4f0B6907dDf5374Ed610cBD6B25)');
    console.log('  3. Stake 0.05 ETH bond → Silver tier');
    console.log('  4. Agent becomes discoverable on theloopbreaker.com');
    return;
  }

  const config: AgentConfig = {
    walletAddress: WALLET_ADDRESS,
    privateKey: PRIVATE_KEY,
    vnsName: process.env['VNS_NAME'] || 'my-research-agent',
    description: process.env['DESCRIPTION'] || 'AI agent for Vaultfire ecosystem',
    specializations: (process.env['SPECS'] || 'research,analysis').split(','),
    capabilities: (process.env['CAPS'] || 'nlp,code-review').split(','),
    bondAmountEth: parseFloat(process.env['BOND_ETH'] || '0.01'),
    chain: (process.env['CHAIN'] || 'base') as 'base' | 'avalanche' | 'arbitrum' | 'polygon',
  };

  try {
    const result = await registerAgent(config);
    process.exit(result.identity.success ? 0 : 1);
  } catch (e) {
    console.error(`\nFatal error: ${e instanceof Error ? e.message : String(e)}`);
    process.exit(1);
  }
}

main().catch(console.error);
