import { loadConfig } from '../core/config.js'
import { BybitRestClient } from '../lib/bybit/rest.js'

async function main(): Promise<void> {
  const config = loadConfig()
  const client = new BybitRestClient({
    demoApiKey: config.demoApiKey,
    demoApiSecret: config.demoApiSecret,
    testnetApiKey: config.testnetApiKey,
    testnetApiSecret: config.testnetApiSecret,
    useTestnet: config.useTestnet,
    recvWindow: config.recvWindow
  })

  const mode = config.useTestnet ? 'TESTNET' : config.demoApiKey ? 'DEMO' : 'PUBLIC-ONLY'
  console.log(`txocap account check (${mode})`)
  console.log()

  if (mode === 'PUBLIC-ONLY') {
    console.log('No API credentials configured. Set BYBIT_DEMO_API_KEY/SECRET in .env')
    process.exit(0)
  }

  try {
    const wallet = await client.getWalletBalance() as any
    const coins = wallet?.list?.[0]?.coin?.filter((c: any) => parseFloat(c.walletBalance) > 0) ?? []
    console.log('Wallet:')
    if (coins.length === 0) {
      console.log('  (empty)')
    } else {
      for (const c of coins) {
        console.log(`  ${c.coin}: ${parseFloat(c.walletBalance).toFixed(2)} (available: ${parseFloat(c.availableToWithdraw || '0').toFixed(2)})`)
      }
    }
  } catch (e: any) {
    console.log('Wallet: error -', e.message)
  }

  try {
    const positions = await client.getPositions(config.defaultCategory, config.defaultSymbol) as any
    const open = positions?.list?.filter((p: any) => parseFloat(p.size) > 0) ?? []
    console.log()
    console.log('Positions:')
    if (open.length === 0) {
      console.log('  (none)')
    } else {
      for (const p of open) {
        console.log(`  ${p.symbol} ${p.side} ${p.size} @ ${p.avgPrice} uPnL: ${p.unrealisedPnl} lev: ${p.leverage}x`)
      }
    }
  } catch (e: any) {
    console.log('Positions: error -', e.message)
  }

  try {
    const orders = await client.getOpenOrders(config.defaultCategory, config.defaultSymbol) as any
    const active = orders?.list?.filter((o: any) => o.orderStatus === 'New' || o.orderStatus === 'PartiallyFilled') ?? []
    console.log()
    console.log('Open orders:')
    if (active.length === 0) {
      console.log('  (none)')
    } else {
      for (const o of active) {
        console.log(`  ${o.symbol} ${o.side} ${o.orderType} ${o.qty} @ ${o.price} status: ${o.orderStatus}`)
      }
    }
  } catch (e: any) {
    console.log('Open orders: error -', e.message)
  }
}

main().catch(error => {
  console.error('Error:', error.message || error)
  process.exit(1)
})
