import { ethers, upgrades } from "hardhat";

/**
 * 部署WUSD代币
 */
async function main() {
  console.log("开始部署WUSD代币...\n");

  const [deployer] = await ethers.getSigners();
  console.log("部署账户:", deployer.address);
  console.log("账户余额:", ethers.formatEther(await ethers.provider.getBalance(deployer.address)), "ETH\n");

  // ===== 部署WUSD (可升级) =====
  console.log("===== 部署WUSD (可升级) =====");
  const WUSD = await ethers.getContractFactory("WUSD");
  
  console.log("部署WUSD代理...");
  const wusd = await upgrades.deployProxy(
    WUSD,
    ["Wrapped USD", "WUSD"],
    {
      initializer: "initialize",
      kind: "uups",
    }
  );
  await wusd.waitForDeployment();
  const wusdAddress = await wusd.getAddress();
  console.log("✅ WUSD代理部署到:", wusdAddress);

  const wusdImplAddress = await upgrades.erc1967.getImplementationAddress(wusdAddress);
  console.log("✅ WUSD实现地址:", wusdImplAddress);

  // 验证部署
  const name = await wusd.name();
  const symbol = await wusd.symbol();
  const decimals = await wusd.decimals();
  console.log("\n代币信息:");
  console.log("  名称:", name);
  console.log("  符号:", symbol);
  console.log("  精度:", decimals.toString());

  // ===== 显示部署摘要 =====
  console.log("\n===== 部署摘要 =====");
  console.log("WUSD代理:", wusdAddress);
  console.log("WUSD实现:", wusdImplAddress);

  // 保存到JSON文件
  const deploymentInfo = {
    network: (await ethers.provider.getNetwork()).name,
    chainId: (await ethers.provider.getNetwork()).chainId.toString(),
    deployer: deployer.address,
    timestamp: new Date().toISOString(),
    contracts: {
      WUSD: {
        proxy: wusdAddress,
        implementation: wusdImplAddress,
        name: name,
        symbol: symbol,
        decimals: Number(decimals)
      }
    }
  };

  const fs = require("fs");
  fs.writeFileSync(
    "./deployments-wusd.json",
    JSON.stringify(deploymentInfo, null, 2)
  );
  console.log("\n✅ 部署信息已保存到 deployments-wusd.json");
}

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