import { ethers } from "hardhat";

/**
 * VKP Mainnet Deployment Script
 * Deploys: KeyVault, SessionKeyManager, DelegationRegistry, VKPFactory
 * to Base, Avalanche, Arbitrum, and Polygon mainnets.
 * 
 * Each chain uses its own live Vaultfire registry addresses.
 */

interface ChainConfig {
  name: string;
  identityRegistry: string;
  bondsRegistry: string;       // AIAccountabilityBonds
  reputationRegistry: string;
}

const CHAINS: Record<string, ChainConfig> = {
  base: {
    name: "Base",
    identityRegistry: "0xa7BD20bf5De63df949cA5Be2F20835978eCba81A",
    bondsRegistry: "0x6750D28865434344e04e1D0a6044394b726C3dfE",       // AIAccountabilityBonds
    reputationRegistry: "0x98afd1440B2238D73c1394720277a6d031fCbbD0",
  },
  avalanche: {
    name: "Avalanche",
    identityRegistry: "0x7448057C95Fb8a8B974a566cdcc9Cd042166A3f8",
    bondsRegistry: "0x376831fB2457E34559891c32bEb61c442053C066",       // AIAccountabilityBonds
    reputationRegistry: "0x5DB1B4b412b80d03819395794fCcF5A73BF30656",
  },
  arbitrum: {
    name: "Arbitrum",
    identityRegistry: "0x83dd216449B3F0574E39043ECFE275946fa492e9",
    bondsRegistry: "0xef3A944f4d7bb376699C83A29d7Cb42C90D9B6F0",       // AIAccountabilityBonds
    reputationRegistry: "0x8B8Ba34F8AAB800F0Ba8391fb1388c6EFb911F92",
  },
  polygon: {
    name: "Polygon",
    identityRegistry: "0xD9bF6D92a1D9ee44a48c38481c046a819CBdf2ba",
    bondsRegistry: "0xdB54B8925664816187646174bdBb6Ac658A55a5F",       // AIAccountabilityBonds
    reputationRegistry: "0x54e00081978eE2C8d9Ada8e9975B0Bb543D06A55",
  },
};

async function deployToChain(chainKey: string) {
  const config = CHAINS[chainKey];
  if (!config) throw new Error(`Unknown chain: ${chainKey}`);

  const [deployer] = await ethers.getSigners();
  console.log(`\n${"═".repeat(60)}`);
  console.log(`Deploying VKP to ${config.name}`);
  console.log(`Deployer: ${deployer.address}`);
  const balance = await ethers.provider.getBalance(deployer.address);
  console.log(`Balance: ${ethers.formatEther(balance)} native`);
  console.log(`${"═".repeat(60)}`);

  // 1. Deploy SessionKeyManager
  console.log("\n[1/4] Deploying SessionKeyManager...");
  const SKM = await ethers.getContractFactory("SessionKeyManager");
  const skm = await SKM.deploy(config.identityRegistry);
  await skm.waitForDeployment();
  const skmAddr = await skm.getAddress();
  console.log(`  SessionKeyManager: ${skmAddr}`);

  // 2. Deploy DelegationRegistry
  console.log("[2/4] Deploying DelegationRegistry...");
  const DR = await ethers.getContractFactory("DelegationRegistry");
  const dr = await DR.deploy(
    config.identityRegistry,
    config.bondsRegistry,
    config.reputationRegistry
  );
  await dr.waitForDeployment();
  const drAddr = await dr.getAddress();
  console.log(`  DelegationRegistry: ${drAddr}`);

  // 3. Deploy VKPFactory
  console.log("[3/4] Deploying VKPFactory...");
  const Factory = await ethers.getContractFactory("VKPFactory");
  const factory = await Factory.deploy(config.identityRegistry);
  await factory.waitForDeployment();
  const factoryAddr = await factory.getAddress();
  console.log(`  VKPFactory: ${factoryAddr}`);

  // Note: KeyVault is deployed via VKPFactory.createVault(), not standalone
  console.log("[4/4] KeyVault — deployed on-demand via VKPFactory.createVault()");

  console.log(`\n✅ ${config.name} deployment complete!`);
  console.log(`  SessionKeyManager: ${skmAddr}`);
  console.log(`  DelegationRegistry: ${drAddr}`);
  console.log(`  VKPFactory: ${factoryAddr}`);

  return {
    chain: config.name,
    sessionKeyManager: skmAddr,
    delegationRegistry: drAddr,
    vkpFactory: factoryAddr,
  };
}

async function main() {
  const chainArg = process.env.DEPLOY_CHAIN;
  if (!chainArg) {
    console.error("Set DEPLOY_CHAIN env var (base, avalanche, arbitrum, polygon)");
    process.exit(1);
  }
  
  const result = await deployToChain(chainArg);
  
  // Output as JSON for parsing
  console.log("\n--- DEPLOYMENT_JSON ---");
  console.log(JSON.stringify(result, null, 2));
  console.log("--- END_DEPLOYMENT_JSON ---");
}

main().catch((error) => {
  console.error(error);
  process.exit(1);
});
