/**
 * Deploy TestUSDT to KAVA Testnet using inline Solidity compilation
 */
import { ethers } from 'ethers';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const solc = require('solc');

const KAVA_TESTNET_RPC = 'https://evm.testnet.kava.io';
const KAVA_TESTNET_CHAIN_ID = 2221;
const privateKey = '0xd42a6e6021ebd884f3f179d3793a32e97b9f1001db6ff44441ec455d748b9aa6';

const sourceCode = `
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;

contract TestUSDT {
    string public constant name = "Test USDT";
    string public constant symbol = "USDT";
    uint8 public constant decimals = 6;
    uint256 public totalSupply;
    mapping(address => uint256) public balanceOf;
    mapping(address => mapping(address => uint256)) public allowance;

    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);

    constructor() {
        _mint(msg.sender, 1000000 * 1e6);
    }

    function _mint(address to, uint256 amount) internal {
        totalSupply += amount;
        balanceOf[to] += amount;
        emit Transfer(address(0), to, amount);
    }

    function transfer(address to, uint256 amount) public returns (bool) {
        balanceOf[msg.sender] -= amount;
        balanceOf[to] += amount;
        emit Transfer(msg.sender, to, amount);
        return true;
    }

    function approve(address spender, uint256 amount) public returns (bool) {
        allowance[msg.sender][spender] = amount;
        emit Approval(msg.sender, spender, amount);
        return true;
    }

    function transferFrom(address from, address to, uint256 amount) public returns (bool) {
        allowance[from][msg.sender] -= amount;
        balanceOf[from] -= amount;
        balanceOf[to] += amount;
        emit Transfer(from, to, amount);
        return true;
    }

    function mint(uint256 amount) external {
        _mint(msg.sender, amount);
    }

    function faucet() external {
        _mint(msg.sender, 10000 * 1e6);
    }
}
`;

async function deploy() {
  console.log('🔨 Compiling contract...');

  const input = {
    language: 'Solidity',
    sources: { 'TestUSDT.sol': { content: sourceCode } },
    settings: { outputSelection: { '*': { '*': ['abi', 'evm.bytecode'] } } },
  };

  const output = JSON.parse(solc.compile(JSON.stringify(input)));

  if (output.errors) {
    const errors = output.errors.filter((e: any) => e.severity === 'error');
    if (errors.length > 0) {
      console.error('❌ Compilation errors:', errors);
      process.exit(1);
    }
  }

  const contract = output.contracts['TestUSDT.sol']['TestUSDT'];
  const bytecode = contract.evm.bytecode.object;
  const compiledAbi = contract.abi;

  console.log('🌐 Connecting to KAVA Testnet...');
  const provider = new ethers.JsonRpcProvider(KAVA_TESTNET_RPC, {
    chainId: KAVA_TESTNET_CHAIN_ID,
    name: 'kava-testnet',
  });

  const wallet = new ethers.Wallet(privateKey, provider);
  console.log(`📍 Deployer: ${wallet.address}`);

  const balance = await provider.getBalance(wallet.address);
  console.log(`💰 Balance: ${ethers.formatEther(balance)} TKAVA`);

  if (balance < ethers.parseEther('0.01')) {
    console.error('❌ Insufficient TKAVA');
    process.exit(1);
  }

  console.log('📦 Deploying...');
  const factory = new ethers.ContractFactory(compiledAbi, bytecode, wallet);
  const deployedContract = await factory.deploy({
    gasLimit: 5000000,
  });

  console.log(`⏳ Waiting for confirmation...`);
  console.log(`   TX: https://testnet.kavascan.com/tx/${deployedContract.deploymentTransaction()?.hash}`);

  await deployedContract.waitForDeployment();

  const address = await deployedContract.getAddress();
  console.log('');
  console.log('='.repeat(60));
  console.log(`✅ SUCCESS! TestUSDT deployed on KAVA Testnet`);
  console.log(`📋 Contract Address: ${address}`);
  console.log('='.repeat(60));
  console.log('');
  console.log(`🔗 KavaScan: https://testnet.kavascan.com/address/${address}`);
  console.log('');
  console.log('Next: Update KAVA_USDT_CONTRACT in .env');
}

deploy().catch((e) => {
  console.error('❌ Error:', e.message);
  process.exit(1);
});
