import { VenicePlugin } from '../index';
import dotenv from 'dotenv';
import { ethers } from 'ethers';

// Load environment variables
dotenv.config();

async function main() {
  try {
    // Initialize the plugin with configuration from environment variables
    const venicePlugin = new VenicePlugin({
      rpcUrl: "https://mainnet.base.org",
      privateKey: process.env.PRIVATE_KEY, // Optional, for write operations
      stakingContractAddress: process.env.STAKING_CONTRACT_ADDRESS || '0x321b7ff75154472B18EDb199033fF4D116F340Ff'
    });

    // Initialize the plugin
    await venicePlugin.initialize();
    console.log('Plugin initialized successfully');

    // Get wallet address if private key is provided
    let userAddress = process.env.USER_ADDRESS || '';
    if (process.env.PRIVATE_KEY) {
      const provider = new ethers.JsonRpcProvider("https://mainnet.base.org");
      const wallet = new ethers.Wallet(process.env.PRIVATE_KEY, provider);
      userAddress = wallet.address;
      console.log(`Connected wallet address: ${userAddress}`);
    }

    // Check VVV token balance if we have a user address
    if (userAddress) {
      const tokenBalance = await venicePlugin.getTokenBalance(userAddress);
      if (tokenBalance.success) {
        console.log(`\nVVV Token Balance: ${tokenBalance.data.formatted} VVV`);
      } else {
        console.error(`Failed to get token balance: ${tokenBalance.error}`);
      }

      // Check staking allowance
      const allowance = await venicePlugin.checkAllowance(userAddress);
      if (allowance.success) {
        console.log(`Staking Allowance: ${allowance.data.formatted} VVV`);
      } else {
        console.error(`Failed to get allowance: ${allowance.error}`);
      }
    }

    // Example: Get staking statistics
    const stats = await venicePlugin.getStakingStats();
    if (stats.success) {
      console.log('\nStaking contract statistics:');
      console.log(`- Total staked: ${stats.data.totalStaked} VVV`);
      console.log(`- Emission rate: ${stats.data.emissionRate} VVV per second`);
      console.log(`- Cooldown duration: ${stats.data.cooldownDuration} seconds (${Number(stats.data.cooldownDuration) / 86400} days)`);
      console.log(`- Venice percentage: ${stats.data.venicePercentage}`);
      console.log(`- Last reward timestamp: ${new Date(Number(stats.data.lastRewardTimestamp) * 1000).toISOString()}`);
    } else {
      console.error(`Failed to get staking stats: ${stats.error}`);
    }

    // Example: Get user staking information (if we have a user address)
    if (userAddress) {
      try {
        const userInfo = await venicePlugin.getUserStakeInfo(userAddress);
        if (userInfo.success) {
          console.log('\nUser staking information:');
          console.log(`- Staked amount: ${userInfo.data.stakeAmount} VVV`);
          console.log(`- Pending rewards: ${userInfo.data.pendingRewards} VVV`);
          console.log(`- Cooldown amount: ${userInfo.data.stakeInfo.cooldownAmount} VVV`);
          
          const cooldownEnd = Number(userInfo.data.stakeInfo.cooldownEnd);
          if (cooldownEnd > 0) {
            const now = Math.floor(Date.now() / 1000);
            if (cooldownEnd > now) {
              console.log(`- Cooldown ends: ${new Date(cooldownEnd * 1000).toISOString()} (${(cooldownEnd - now) / 86400} days remaining)`);
            } else {
              console.log(`- Cooldown ended: ${new Date(cooldownEnd * 1000).toISOString()} (ready to finalize)`);
            }
          } else {
            console.log('- No active cooldown');
          }
        } else {
          console.error(`Failed to get user info: ${userInfo.error}`);
        }
      } catch (error) {
        console.error(`Error fetching staking info: ${error instanceof Error ? error.message : String(error)}`);
      }
    }

    // Cleanup
    await venicePlugin.cleanup();
    console.log('\nPlugin cleaned up successfully');
  } catch (error) {
    console.error('Error in example:', error);
  }
}

// Run the example
main().catch(console.error); 