import { ethers } from "hardhat";

/**
 * Vaultfire v2 — Agent Protection Layer Deployment
 * Deploys 6 new contracts to all 4 chains:
 *   1. AgentInsurancePool
 *   2. AgentSafetyManager
 *   3. ComplianceRegistry
 *   4. ReputationDecay
 *   5. ScopedDelegation
 *   6. AgentSLAEnforcer
 */

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

const CHAINS: Record<string, ChainConfig> = {
  base: {
    name: "Base",
    identityRegistry: "0xa7BD20bf5De63df949cA5Be2F20835978eCba81A",
    bondsRegistry: "0x6750D28865434344e04e1D0a6044394b726C3dfE",
    reputationRegistry: "0x98afd1440B2238D73c1394720277a6d031fCbbD0",
  },
  avalanche: {
    name: "Avalanche",
    identityRegistry: "0x7448057C95Fb8a8B974a566cdcc9Cd042166A3f8",
    bondsRegistry: "0x376831fB2457E34559891c32bEb61c442053C066",
    reputationRegistry: "0x5DB1B4b412b80d03819395794fCcF5A73BF30656",
  },
  arbitrum: {
    name: "Arbitrum",
    identityRegistry: "0x83dd216449B3F0574E39043ECFE275946fa492e9",
    bondsRegistry: "0xef3A944f4d7bb376699C83A29d7Cb42C90D9B6F0",
    reputationRegistry: "0x8B8Ba34F8AAB800F0Ba8391fb1388c6EFb911F92",
  },
  polygon: {
    name: "Polygon",
    identityRegistry: "0xD9bF6D92a1D9ee44a48c38481c046a819CBdf2ba",
    bondsRegistry: "0xdB54B8925664816187646174bdBb6Ac658A55a5F",
    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 Vaultfire v2 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. AgentInsurancePool
  console.log("\n[1/6] Deploying AgentInsurancePool...");
  const Insurance = await ethers.getContractFactory("AgentInsurancePool");
  const insurance = await Insurance.deploy(
    config.identityRegistry,
    config.bondsRegistry,
    config.reputationRegistry
  );
  await insurance.waitForDeployment();
  const insuranceAddr = await insurance.getAddress();
  console.log(`  AgentInsurancePool: ${insuranceAddr}`);

  // 2. AgentSafetyManager
  console.log("[2/6] Deploying AgentSafetyManager...");
  const Safety = await ethers.getContractFactory("AgentSafetyManager");
  const safety = await Safety.deploy(
    config.identityRegistry,
    config.bondsRegistry,
    config.reputationRegistry
  );
  await safety.waitForDeployment();
  const safetyAddr = await safety.getAddress();
  console.log(`  AgentSafetyManager: ${safetyAddr}`);

  // 3. ComplianceRegistry
  console.log("[3/6] Deploying ComplianceRegistry...");
  const Compliance = await ethers.getContractFactory("ComplianceRegistry");
  const compliance = await Compliance.deploy(config.identityRegistry);
  await compliance.waitForDeployment();
  const complianceAddr = await compliance.getAddress();
  console.log(`  ComplianceRegistry: ${complianceAddr}`);

  // 4. ReputationDecay
  console.log("[4/6] Deploying ReputationDecay...");
  const Decay = await ethers.getContractFactory("ReputationDecay");
  const decay = await Decay.deploy(
    config.identityRegistry,
    config.reputationRegistry
  );
  await decay.waitForDeployment();
  const decayAddr = await decay.getAddress();
  console.log(`  ReputationDecay: ${decayAddr}`);

  // 5. ScopedDelegation
  console.log("[5/6] Deploying ScopedDelegation...");
  const Scoped = await ethers.getContractFactory("ScopedDelegation");
  const scoped = await Scoped.deploy(
    config.identityRegistry,
    config.bondsRegistry,
    config.reputationRegistry
  );
  await scoped.waitForDeployment();
  const scopedAddr = await scoped.getAddress();
  console.log(`  ScopedDelegation: ${scopedAddr}`);

  // 6. AgentSLAEnforcer
  console.log("[6/6] Deploying AgentSLAEnforcer...");
  const SLA = await ethers.getContractFactory("AgentSLAEnforcer");
  const slaContract = await SLA.deploy(
    config.identityRegistry,
    config.bondsRegistry,
    config.reputationRegistry
  );
  await slaContract.waitForDeployment();
  const slaAddr = await slaContract.getAddress();
  console.log(`  AgentSLAEnforcer: ${slaAddr}`);

  const result = {
    chain: config.name,
    agentInsurancePool: insuranceAddr,
    agentSafetyManager: safetyAddr,
    complianceRegistry: complianceAddr,
    reputationDecay: decayAddr,
    scopedDelegation: scopedAddr,
    agentSLAEnforcer: slaAddr,
  };

  console.log(`\n✅ ${config.name} v2 deployment complete!`);
  console.log(JSON.stringify(result, null, 2));

  return result;
}

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);

  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);
});
