/**
 * Example: Register a .vns name
 *
 * IMPORTANT SECURITY NOTE:
 * Never hardcode private keys in production code.
 * Use environment variables or a secure key management system.
 *
 * This example requires:
 * - A wallet with ETH/native token on Base mainnet for gas
 * - For agent registration: minimum 0.01 ETH for the accountability bond
 *
 * Run: PRIVATE_KEY=0x... WALLET=0x... npx ts-node examples/register-name.ts
 */

import {
  registerVNSName,
  validateVNSName,
  checkVNSAvailability,
  estimateVNSRegistrationGas,
  validateRegistrationRules,
} from '../src/index.js';

async function main() {
  // Load from environment (never hardcode!)
  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/register-name.ts');
    console.log('\nRunning in demo mode (no actual transaction)...\n');
    await demoMode();
    return;
  }

  const VNS_NAME = process.env['VNS_NAME'] || 'my-human-identity';
  const IDENTITY_TYPE = (process.env['IDENTITY_TYPE'] || 'human') as 'human' | 'companion' | 'agent';

  console.log('Vaultfire Name Service — Registration\n');
  console.log(`Name:     ${VNS_NAME}.vns`);
  console.log(`Type:     ${IDENTITY_TYPE}`);
  console.log(`Wallet:   ${WALLET_ADDRESS}`);
  console.log(`Chain:    Base mainnet\n`);

  // Step 1: Validate name format
  const validation = validateVNSName(VNS_NAME);
  if (!validation.valid) {
    console.error(`Name validation failed: ${validation.error}`);
    process.exit(1);
  }
  console.log(`✓ Name format valid: "${validation.normalized}.vns"`);

  // Step 2: Check anti-gaming rules
  const bondAmount = IDENTITY_TYPE === 'agent' ? 0.01 : undefined;
  const ruleError = validateRegistrationRules(WALLET_ADDRESS, IDENTITY_TYPE, VNS_NAME, bondAmount);
  if (ruleError) {
    console.error(`Rule violation: ${ruleError}`);
    process.exit(1);
  }
  console.log(`✓ Anti-gaming rules passed`);

  // Step 3: Check availability
  const availability = await checkVNSAvailability(VNS_NAME);
  if (!availability.available) {
    console.error(`Name is not available: ${availability.error || 'already taken'}`);
    process.exit(1);
  }
  console.log(`✓ Name is available`);

  // Step 4: Estimate gas
  const gasEstimate = await estimateVNSRegistrationGas(WALLET_ADDRESS, VNS_NAME, IDENTITY_TYPE, 'base');
  if (gasEstimate) {
    console.log(`✓ Estimated gas: ${gasEstimate.totalFeeFormatted} ${gasEstimate.gasSymbol}`);
  }

  // Step 5: Register
  console.log(`\nRegistering ${VNS_NAME}.vns as ${IDENTITY_TYPE}...`);

  const result = await registerVNSName(
    WALLET_ADDRESS,
    PRIVATE_KEY,
    VNS_NAME,
    IDENTITY_TYPE,
    'base',
    {
      description: 'Registered via vaultfire-vns SDK',
      bondAmountEth: bondAmount,
    }
  );

  if (result.success) {
    console.log(`\n✓ Registration successful!`);
    console.log(`  Transaction: ${result.txHash}`);
    console.log(`  Explorer:    ${result.explorerUrl}`);
    console.log(`  Message:     ${result.message}`);
  } else {
    console.error(`\n✗ Registration failed: ${result.message}`);
    console.error(`  Error type: ${result.errorType}`);
    process.exit(1);
  }
}

async function demoMode() {
  console.log('Demo: Simulating registration flow (no actual transactions)\n');

  const scenarios = [
    { name: 'alice-human', type: 'human' as const, bond: undefined },
    { name: 'alice-companion', type: 'companion' as const, bond: undefined },
    { name: 'my-research-agent', type: 'agent' as const, bond: 0.01 },
    { name: 'invalid--name', type: 'human' as const, bond: undefined },
  ];

  for (const scenario of scenarios) {
    console.log(`Scenario: "${scenario.name}" (${scenario.type})`);

    const validation = validateVNSName(scenario.name);
    if (!validation.valid) {
      console.log(`  ✗ Invalid name: ${validation.error}\n`);
      continue;
    }

    const avail = await checkVNSAvailability(scenario.name);
    if (!avail.available) {
      console.log(`  ✗ Name taken: ${avail.takenBy ?? 'unknown owner'}\n`);
      continue;
    }

    if (scenario.type === 'agent' && (!scenario.bond || scenario.bond < 0.01)) {
      console.log(`  ✗ Agent requires minimum 0.01 ETH bond\n`);
      continue;
    }

    console.log(`  ✓ Ready to register "${validation.normalized}.vns"`);
    console.log(`  Gas: call estimateVNSRegistrationGas() for estimate`);
    if (scenario.bond) {
      console.log(`  Bond: ${scenario.bond} ETH required`);
    }
    console.log('');
  }
}

main().catch(console.error);
