import { ethers } from "hardhat";

/**
 * Polygon-specific deploy with gas price override to handle stuck nonce
 */

const CONFIG = {
  identityRegistry: "0xD9bF6D92a1D9ee44a48c38481c046a819CBdf2ba",
  bondsRegistry: "0xdB54B8925664816187646174bdBb6Ac658A55a5F",
  reputationRegistry: "0x54e00081978eE2C8d9Ada8e9975B0Bb543D06A55",
};

async function main() {
  const [deployer] = await ethers.getSigners();
  const balance = await ethers.provider.getBalance(deployer.address);
  console.log(`Deployer: ${deployer.address}`);
  console.log(`Balance: ${ethers.formatEther(balance)} MATIC`);

  // Get current gas price and bump it 50% to replace any stuck txns
  const feeData = await ethers.provider.getFeeData();
  const gasPrice = (feeData.gasPrice! * 150n) / 100n;
  console.log(`Gas price: ${ethers.formatUnits(gasPrice, "gwei")} gwei (1.5x current)`);

  const overrides = { gasPrice };

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

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

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

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

  console.log("\n--- DEPLOYMENT_JSON ---");
  console.log(JSON.stringify({
    chain: "Polygon",
    sessionKeyManager: skmAddr,
    delegationRegistry: drAddr,
    vkpFactory: factoryAddr,
  }, null, 2));
  console.log("--- END_DEPLOYMENT_JSON ---");
}

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