import type { Address, WalletCapabilities } from 'viem'
import type { Config } from 'wagmi'
import { getWalletClient } from 'wagmi/actions'

const TIMEOUT_MS = 10000

export async function getWalletCapabilities(config: Config, account: Address): Promise<WalletCapabilities | null> {
  let timeoutId: ReturnType<typeof setTimeout> | undefined

  const timeoutPromise = new Promise((_, reject) => {
    timeoutId = setTimeout(() => reject(new Error('getCapabilities timeout')), TIMEOUT_MS)
  })

  try {
    const walletClient = await getWalletClient(config);

    const capabilities = await Promise.race([
      walletClient?.getCapabilities({account}),
      timeoutPromise,
    ])

    if (capabilities && typeof capabilities === 'object') {
      return capabilities as WalletCapabilities
    }
    
    throw new Error(`Invalid capabilities format: ${JSON.stringify(capabilities)}`)
  } catch (err) {
    console.warn('[Capabilities]', err)
    return null
  } finally {
    if (timeoutId) clearTimeout(timeoutId)
  }
}
