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

const PRIVATE_KEY = '0x886ea4cffe76c386fecf3ff321ac9ae913737c46c17bc6ce2413752144668a2a';
const RPC_URL = 'https://evm.kava.io';

// Contract bytecode
const BYTECODE = '0x' + fs.readFileSync('build/DurianUSDT.bin', 'utf8');
const ABI = JSON.parse(fs.readFileSync('build/DurianUSDT.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');

    // 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 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), 'dUSDT');
    console.log('Owner balance:', ethers.formatUnits(ownerBalance, 6), 'dUSDT');

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

deploy().catch(console.error);
