import { ethers } from 'ethers';
import fs from 'fs';

// Same deployer account as dUSDT
const PRIVATE_KEY = '0x886ea4cffe76c386fecf3ff321ac9ae913737c46c17bc6ce2413752144668a2a';
const RPC_URL = 'https://evm.kava.io';

// Contract bytecode
const BYTECODE = '0x' + fs.readFileSync('build/EnergyUSDT.bin', 'utf8');
const ABI = JSON.parse(fs.readFileSync('build/EnergyUSDT.abi', 'utf8'));

async function deploy() {
    // Connect to Kava mainnet
    const provider = new ethers.JsonRpcProvider(RPC_URL);
    const wallet = new ethers.Wallet(PRIVATE_KEY, provider);

    console.log('Deployer address:', wallet.address);

    // Check balance
    const balance = await provider.getBalance(wallet.address);
    console.log('Balance:', ethers.formatEther(balance), 'KAVA');

    if (parseFloat(ethers.formatEther(balance)) < 0.01) {
        console.error('Insufficient KAVA balance for deployment!');
        process.exit(1);
    }

    // Get network info
    const network = await provider.getNetwork();
    console.log('Chain ID:', network.chainId.toString());

    // Create contract factory
    const factory = new ethers.ContractFactory(ABI, BYTECODE, wallet);

    console.log('Deploying EnergyUSDT (eUSDT) contract...');

    // Deploy
    const contract = await factory.deploy();
    console.log('Transaction hash:', contract.deploymentTransaction().hash);

    // Wait for deployment
    console.log('Waiting for confirmation...');
    await contract.waitForDeployment();

    const contractAddress = await contract.getAddress();
    console.log('Contract deployed at:', contractAddress);

    // Verify deployment
    console.log('\nVerifying deployment...');
    const name = await contract.name();
    const symbol = await contract.symbol();
    const decimals = await contract.decimals();
    const totalSupply = await contract.totalSupply();
    const ownerBalance = await contract.balanceOf(wallet.address);

    console.log('Token name:', name);
    console.log('Token symbol:', symbol);
    console.log('Decimals:', decimals.toString());
    console.log('Total supply:', ethers.formatUnits(totalSupply, 6), 'eUSDT');
    console.log('Owner balance:', ethers.formatUnits(ownerBalance, 6), 'eUSDT');

    console.log('\n=== DEPLOYMENT COMPLETE ===');
    console.log('Contract Address:', contractAddress);
    console.log('Explorer:', `https://kavascan.com/address/${contractAddress}`);

    // Save deployment info
    const deploymentInfo = {
        network: 'KAVA Mainnet',
        chainId: 2222,
        contractAddress,
        deployer: wallet.address,
        transactionHash: contract.deploymentTransaction().hash,
        deployedAt: new Date().toISOString(),
        token: {
            name,
            symbol,
            decimals: decimals.toString(),
            totalSupply: totalSupply.toString()
        }
    };

    fs.writeFileSync('deployment.json', JSON.stringify(deploymentInfo, null, 2));
    console.log('\nDeployment info saved to deployment.json');
}

deploy().catch(console.error);
