const { ethers } = require("hardhat");

// Identity Registry addresses per chain
const IDENTITY_REGISTRIES = {
  base:      "0xa7BD20bf5De63df949cA5Be2F20835978eCba81A",
  avalanche: "0x7448057C95Fb8a8B974a566cdcc9Cd042166A3f8",
  arbitrum:  "0x83dd216449B3F0574E39043ECFE275946fa492e9",
  polygon:   "0xD9bF6D92a1D9ee44a48c38481c046a819CBdf2ba",
};

async function deployOne(name, args, deployer) {
  // Wait a moment between deploys to let nonce propagate
  await new Promise(r => setTimeout(r, 5000));
  const nonce = await ethers.provider.getTransactionCount(deployer.address, "pending");
  console.log(`   Deploying with nonce ${nonce}...`);
  const Factory = await ethers.getContractFactory(name);
  const contract = await Factory.deploy(...args, { nonce });
  await contract.waitForDeployment();
  const addr = await contract.getAddress();
  console.log(`   ${name}: ${addr}`);
  return addr;
}

async function main() {
  const [deployer] = await ethers.getSigners();
  const network = hre.network.name;
  const identityRegistry = IDENTITY_REGISTRIES[network];

  if (!identityRegistry) {
    throw new Error(`No identity registry configured for network: ${network}`);
  }

  console.log(`\n=== Deploying 5 new Vaultfire contracts on ${network} ===`);
  console.log(`Deployer: ${deployer.address}`);
  console.log(`Identity Registry: ${identityRegistry}`);
  console.log(`Balance: ${ethers.formatEther(await ethers.provider.getBalance(deployer.address))} ETH\n`);

  const results = {};

  // 1. VaultfireReputationStaking
  console.log("1/5 VaultfireReputationStaking");
  results.reputation_staking = await deployOne("VaultfireReputationStaking", [identityRegistry], deployer);

  // 2. VaultfireTrustOracle
  console.log("2/5 VaultfireTrustOracle");
  results.trust_oracle = await deployOne("VaultfireTrustOracle", [identityRegistry], deployer);

  // 3. VaultfireBondInsurancePool
  console.log("3/5 VaultfireBondInsurancePool");
  results.bond_insurance_pool = await deployOne("VaultfireBondInsurancePool", [identityRegistry], deployer);

  // 4. VaultfireCapabilityCredentials
  console.log("4/5 VaultfireCapabilityCredentials");
  results.capability_credentials = await deployOne("VaultfireCapabilityCredentials", [identityRegistry], deployer);

  // 5. VaultfireDisputeResolution
  console.log("5/5 VaultfireDisputeResolution");
  results.dispute_resolution = await deployOne("VaultfireDisputeResolution", [identityRegistry], deployer);

  console.log(`\n=== All 5 contracts deployed on ${network} ===`);
  console.log(JSON.stringify(results, null, 2));

  const remaining = ethers.formatEther(await ethers.provider.getBalance(deployer.address));
  console.log(`\nRemaining balance: ${remaining} ETH`);
}

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