import { cookieStorage, createStorage } from "@wagmi/core";
import { WagmiAdapter } from "@reown/appkit-adapter-wagmi";
import {
  mainnet,
  arbitrum,
  optimism,
  polygon,
  base,
  sepolia,
  bsc,
  avalanche,
} from "@reown/appkit/networks";
import type { AppKitNetwork } from "@reown/appkit/networks";

export interface RuntimeConfig {
  projectId: string;
  wsUrl: string;
}

let cachedConfig: RuntimeConfig | null = null;

export async function getRuntimeConfig(): Promise<RuntimeConfig> {
  if (cachedConfig) return cachedConfig;

  // In production (embedded in Rust binary), config is served from same origin.
  // In dev, proxy is on port 8545.
  const baseUrl =
    process.env.NODE_ENV === "development" ? "http://localhost:8545" : "";

  const resp = await fetch(`${baseUrl}/api/config`);
  const data = await resp.json();

  // If wsUrl is empty, derive from current page location (same-origin mode)
  if (!data.wsUrl) {
    const proto = window.location.protocol === "https:" ? "wss:" : "ws:";
    data.wsUrl = `${proto}//${window.location.host}/ws`;
  }

  cachedConfig = data;
  return cachedConfig!;
}

export const networks: [AppKitNetwork, ...AppKitNetwork[]] = [
  mainnet,
  arbitrum,
  optimism,
  polygon,
  base,
  sepolia,
  bsc,
  avalanche,
];

export function createWagmiAdapter(projectId: string) {
  return new WagmiAdapter({
    storage: createStorage({ storage: cookieStorage }),
    ssr: true,
    projectId,
    networks,
  });
}
