import { ExecKernelClient, ExecKernelError } from '@execkernel/sdk';
import type { DeepReadonly, Payload } from '@execkernel/sdk';

type DeliveryView =
  | { heading: string; choices: { edgeId: number; label: string; enabled: boolean }[] }
  | { heading: string; messages: string[] };

function deliveryView(payload: DeepReadonly<Payload> | null): DeliveryView {
  if (!payload) throw new Error('The service did not return a displayable payload.');

  if (payload.type === 'node') {
    return {
      heading: payload.title ?? '',
      choices: payload.edges.map(edge => ({
        edgeId: edge.id,
        label: edge.label ?? String(edge.id),
        enabled: edge.enabled !== false,
      })),
    };
  }

  return {
    heading: payload.title ?? '',
    messages: payload.outputs.flatMap(output =>
      output.type === 'content' && typeof output.content === 'string'
        ? [output.content]
        : []),
  };
}

async function main(): Promise<void> {
  const baseUrl = process.env.EXECKERNEL_BASE_URL;
  const apiKey = process.env.EXECKERNEL_API_TOKEN;
  const lang = process.env.EXECKERNEL_LANG || 'en';

  if (!baseUrl || !apiKey) {
    throw new Error('Set EXECKERNEL_BASE_URL and EXECKERNEL_API_TOKEN.');
  }

  const client = new ExecKernelClient({
    baseUrl,
    apiKey,
    flowId: 'delivery-options',
    lang,
  });

  const session = await client.startSession({ delivery_available: true });
  const sessionId = session.sessionId;
  if (!sessionId) throw new Error('The service did not return a session identifier.');
  const choices = deliveryView(session.currentPayload);

  const payload = await session.selectEdge(20);
  const confirmation = deliveryView(payload);

  const resumed = await client.restoreSession(sessionId);

  console.log(JSON.stringify({
    sessionId,
    choices,
    confirmation,
    resumedNode: resumed.currentPayload?.nodeId,
  }, null, 2));
}

main().catch((error: unknown) => {
  console.error(error instanceof ExecKernelError
    ? error.ekCode + ': ' + error.message
    : error instanceof Error ? error.message : 'Unexpected error');
  process.exitCode = 1;
});
