import { RouterQuote, ExecutionPlan } from './types'
import { walletManager } from '../../infrastructure/wallet/walletManager'
import { AsterAdapter, AsterConfig } from '../../exchanges/aster/asterAdapter'

export class TradeRouter {
  private aster?: AsterAdapter

  constructor() {
    const asterRpc = process.env.ASTER_RPC_URL
    const asterChainId = process.env.ASTER_CHAIN_ID ? Number(process.env.ASTER_CHAIN_ID) : undefined
    const asterRouter = process.env.ASTER_ROUTER_ADDRESS
    if (asterRpc && asterChainId && asterRouter) {
      const cfg: AsterConfig = { rpcUrl: asterRpc, chainId: asterChainId, routerAddress: asterRouter }
      this.aster = new AsterAdapter(cfg, walletManager.wallet || undefined)
    }
  }

  async quoteSpot(symbol: string, quantity: number): Promise<RouterQuote> {
    const price = 0
    return {
      method: 'spot',
      expectedIn: Math.abs(quantity),
      expectedOut: Math.abs(quantity) * price,
      price,
      slippage: 0.0,
      gasEstimateUSD: 0,
      route: 'spot:placeholder',
    }
  }

  async quotePerp(symbol: string, quantity: number): Promise<RouterQuote> {
    if (!this.aster) throw new Error('Aster 适配器未配置')
    const side = quantity > 0 ? 'long' : 'short'
    const q = await this.aster.quote({ symbol, side, quantity: Math.abs(quantity), slippage: 0.005 })
    return {
      method: 'perp',
      expectedIn: Math.abs(quantity),
      expectedOut: Math.abs(quantity) * q.expectedPrice,
      price: q.expectedPrice,
      slippage: 0.0,
      gasEstimateUSD: 0,
      route: 'aster:router',
    }
  }

  async execute(plan: ExecutionPlan) {
    if (plan.method === 'spot') {
      const addr = await walletManager.getAddress()
      return { success: true, txHash: `0xspot_${plan.symbol}_${plan.quantity}_${addr}` }
    } else {
      if (!this.aster) throw new Error('Aster 适配器未配置')
      const side = plan.side === 'buy' ? 'long' : 'short'
      const res = await this.aster.openPerp({
        symbol: plan.symbol,
        side,
        quantity: plan.quantity,
        slippage: 0.005,
        deadlineSec: Math.floor(Date.now() / 1000) + 300,
      })
      return res
    }
  }
}

export const tradeRouter = new TradeRouter()
