/**
 * RPC singleton — breaks the circular import chain.
 *
 * main.ts creates the Electroview and RPC, then sets it here.
 * All other modules import from this file instead of main.ts.
 */

import type { PtyRPCSchema } from '../shared/pty-rpc-schema.ts';

// Placeholder type — matches the shape Electroview.defineRPC returns.
// Uses `any` for the internal Electrobun RPC wrapper type since it is
// not exported from the electrobun package.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type ElectrobunRpc = any;

let _rpc: ElectrobunRpc | null = null;

/** Called once from main.ts after Electroview.defineRPC(). */
export function setAppRpc(rpc: ElectrobunRpc): void {
  _rpc = rpc;
}

/**
 * The app-wide RPC handle.
 * Safe to call after main.ts has executed (Svelte components mount after).
 */
export const appRpc: ElectrobunRpc = new Proxy({} as ElectrobunRpc, {
  get(_target, prop) {
    if (!_rpc) {
      throw new Error(`[rpc] accessed before init — property "${String(prop)}"`);
    }
    return (_rpc as Record<string | symbol, unknown>)[prop];
  },
});
