const { ethers } = require("hardhat");
require("dotenv").config();

/**
 * Deploy CCIPTxReporter to Chain-138
 * This contract reports Chain-138 transactions to Ethereum Mainnet via CCIP
 */
async function main() {
  const [deployer] = await ethers.getSigners();
  console.log("Deploying CCIPTxReporter with account:", deployer.address);
  console.log("Account balance:", (await ethers.provider.getBalance(deployer.address)).toString());

  // Get configuration from environment
  const routerAddress = process.env.CCIP_CHAIN138_ROUTER || process.env.CCIP_ROUTER || ethers.ZeroAddress;
  const destChainSelector = process.env.ETH_MAINNET_SELECTOR || "0x500147"; // Ethereum Mainnet selector (update with actual value from CCIP Directory)
  const destReceiver = process.env.CCIP_LOGGER_ETH_ADDRESS || ethers.ZeroAddress;

  if (routerAddress === ethers.ZeroAddress) {
    throw new Error("CCIP_ROUTER or CCIP_CHAIN138_ROUTER must be set in .env");
  }
  if (destReceiver === ethers.ZeroAddress) {
    throw new Error("CCIP_LOGGER_ETH_ADDRESS must be set in .env (deploy CCIPLogger first)");
  }

  console.log("\nConfiguration:");
  console.log("  Router (Chain-138):", routerAddress);
  console.log("  Destination Chain Selector (Ethereum):", destChainSelector);
  console.log("  Destination Receiver (CCIPLogger):", destReceiver);

  // Deploy CCIPTxReporter
  const CCIPTxReporter = await ethers.getContractFactory("CCIPTxReporter");
  console.log("\nDeploying CCIPTxReporter...");
  
  const selectorU64 = typeof destChainSelector === "string" && destChainSelector.startsWith("0x")
    ? BigInt(destChainSelector)
    : BigInt(destChainSelector);
  const reporter = await CCIPTxReporter.deploy(
    routerAddress,
    selectorU64,
    destReceiver
  );

  await reporter.waitForDeployment();
  const reporterAddress = await reporter.getAddress();

  console.log("\n✅ CCIPTxReporter deployed to:", reporterAddress);
  console.log("\nDeployment details:");
  console.log("  Router:", await reporter.router());
  console.log("  Destination Chain Selector:", await reporter.destChainSelector());
  console.log("  Destination Receiver:", await reporter.destReceiver());
  console.log("  Owner:", await reporter.owner());

  console.log("\n📝 Next steps:");
  console.log("  1. Verify contract on Chain-138 explorer (if available)");
  console.log("  2. Update .env with CCIP_REPORTER_CHAIN138_ADDRESS=" + reporterAddress);
  console.log("  3. Fund the contract with ETH for CCIP fees");
  console.log("  4. Start the watcher/relayer service");
  console.log("  5. Test with a sample transaction report");
}

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