import { InMemoryBroker, InMemoryTransport, MatrixRuntime } from '@open-matrix/core';

import { GreeterActor } from './GreeterActor.js';

interface StandaloneBootContext {
  readonly root?: string;
  readonly mount?: string;
}

interface StandaloneRunnerServices {
  readonly runtime?: MatrixRuntime;
}

function readTrimmedString(value: unknown): string | undefined {
  if (typeof value !== 'string') return undefined;
  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : undefined;
}

function requiredStandaloneRoot(requestedRoot: string | undefined, runtime: MatrixRuntime): string {
  const runtimeRoot = readTrimmedString(runtime.transport.root);
  const root = requestedRoot ?? runtimeRoot;
  if (!root) throw new Error('createStandaloneGreeterActor requires bootContext.root or a runtime transport root');
  return root;
}

export async function createStandaloneGreeterActor(
  _overrides: Record<string, unknown> = {},
  services?: StandaloneRunnerServices,
  _config?: unknown,
  bootContext: StandaloneBootContext = {},
): Promise<{
  runtime: MatrixRuntime;
  actor: GreeterActor;
  root: string;
  mount: string;
}> {
  const requestedRoot = readTrimmedString(bootContext.root);
  const runtime = services?.runtime ?? new MatrixRuntime({
    transport: new InMemoryTransport(new InMemoryBroker(), {
      name: 'demo.greeter-standalone',
      ...(requestedRoot ? { root: requestedRoot } : {}),
    }),
    logging: false,
  });
  const root = requiredStandaloneRoot(requestedRoot, runtime);
  const mount = readTrimmedString(bootContext.mount) ?? 'demo.greeter';
  const actor = await runtime.createSupervised(GreeterActor, mount);
  return { runtime, actor, root, mount };
}
