/**
 * tRPC Client for CLI
 *
 * Type-safe client for communicating with the coordination server.
 * Uses splitLink to route subscriptions to SSE and queries/mutations to HTTP batch.
 */

import { createTRPCClient, httpBatchLink, splitLink, httpSubscriptionLink } from '@trpc/client';
import type { AppRouter } from '../trpc/index.js';

/** Default server port */
const DEFAULT_PORT = 3847;

/** Default server host */
const DEFAULT_HOST = '127.0.0.1';

/**
 * Type-safe tRPC client for the coordination server.
 */
export type TrpcClient = ReturnType<typeof createTRPCClient<AppRouter>>;

/**
 * Creates a tRPC client for the coordination server.
 *
 * @param port - Server port (default: 3847)
 * @param host - Server host (default: 127.0.0.1)
 * @returns Type-safe tRPC client
 */
export function createTrpcClient(
  port: number = DEFAULT_PORT,
  host: string = DEFAULT_HOST
): TrpcClient {
  const url = `http://${host}:${port}/trpc`;
  return createTRPCClient<AppRouter>({
    links: [
      splitLink({
        condition: (op) => op.type === 'subscription',
        true: httpSubscriptionLink({ url }),
        false: httpBatchLink({ url }),
      }),
    ],
  });
}

/**
 * Creates a tRPC client using environment variables or defaults.
 *
 * Uses CW_PORT and CW_HOST environment variables if available,
 * falling back to defaults (127.0.0.1:3847).
 *
 * @returns Type-safe tRPC client
 */
export function createDefaultTrpcClient(): TrpcClient {
  const port = process.env.CW_PORT ? parseInt(process.env.CW_PORT, 10) : DEFAULT_PORT;
  const host = process.env.CW_HOST ?? DEFAULT_HOST;
  return createTrpcClient(port, host);
}
