import { Connection, PublicKey, Keypair } from '@solana/web3.js'

class SolanaWalletService {
  private connection: Connection
  private keypair: Keypair | null = null

  constructor() {
    const rpcUrl = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com'
    this.connection = new Connection(rpcUrl, 'confirmed')
    
    // Initialize keypair from environment
    this.initializeWallet()
  }

  private initializeWallet() {
    try {
      if (process.env.SOLANA_PRIVATE_KEY) {
        const privateKeyArray = JSON.parse(process.env.SOLANA_PRIVATE_KEY)
        this.keypair = Keypair.fromSecretKey(new Uint8Array(privateKeyArray))
        console.log('✅ Solana wallet initialized:', this.keypair.publicKey.toString())
      } else {
        console.warn('⚠️ No SOLANA_PRIVATE_KEY found in environment')
      }
    } catch (error) {
      console.error('❌ Failed to initialize Solana wallet:', error)
    }
  }

  async getWalletBalance(): Promise<{
    solBalance: number
    usdValue: number
    publicKey: string
  }> {
    if (!this.keypair) {
      throw new Error('Wallet not initialized')
    }

    try {
      console.log('💰 Fetching real wallet balance...')
      
      // Get SOL balance
      const balance = await this.connection.getBalance(this.keypair.publicKey)
      const solBalance = balance / 1000000000 // Convert lamports to SOL

      // Get current SOL price
      const priceResponse = await fetch(
        'https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd'
      )
      const priceData = await priceResponse.json()
      const solPrice = priceData.solana?.usd || 0

      const usdValue = solBalance * solPrice

      console.log(`💎 Real wallet balance: ${solBalance.toFixed(4)} SOL ($${usdValue.toFixed(2)})`)

      return {
        solBalance,
        usdValue,
        publicKey: this.keypair.publicKey.toString()
      }
    } catch (error) {
      console.error('❌ Failed to fetch wallet balance:', error)
      throw error
    }
  }

  getPublicKey(): string | null {
    return this.keypair?.publicKey.toString() || null
  }

  isWalletConnected(): boolean {
    return this.keypair !== null
  }
}

export const solanaWalletService = new SolanaWalletService()
export default SolanaWalletService
