import {
  createPublicClient,
  createWalletClient,
  defineChain,
  fallback,
  http,
  publicActions,
} from "viem";
import type { AgentConfig } from "./config.js";
import type { Address } from "viem";

export const robinhoodChain = (rpcUrls: string[]) => defineChain({
  id: 4663,
  name: "Robinhood Chain",
  nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
  rpcUrls: { default: { http: rpcUrls } },
  blockExplorers: {
    default: { name: "Blockscout", url: "https://robinhoodchain.blockscout.com" },
  },
});

export const createChainClients = (config: AgentConfig) => {
  const chain = robinhoodChain(config.rpcUrls);
  const transport = fallback(config.rpcUrls.map((rpcUrl) => http(rpcUrl, { timeout: 15_000, retryCount: 2 })));
  const publicClient = createPublicClient({
    chain,
    transport,
  });
  const walletClient = config.account
    ? createWalletClient({ account: config.account, chain, transport }).extend(publicActions)
    : null;

  return { chain, publicClient, walletClient };
};

export const assertGasReserve = async (
  publicClient: ReturnType<typeof createChainClients>["publicClient"],
  account: Address,
  minimumReserveWei: bigint,
) => {
  const balance = await publicClient.getBalance({ address: account });
  if (balance < minimumReserveWei) {
    throw new Error(`Native balance ${balance} is below MIN_GAS_RESERVE_ETH ${minimumReserveWei}`);
  }
};
