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

type ChoicesView = {
  kind: 'choices';
  nodeId: number;
  heading: string;
  description: string;
  choices: {
    edgeId: number;
    label: string;
    enabled: boolean;
    availability: 'available' | 'blocked' | 'pending' | null;
    reason: string | null;
  }[];
};

type ResultView = {
  kind: 'result';
  nodeId: number;
  heading: string;
  messages: string[];
  links: { kind: 'url' | 'redirect'; label: string; url: string }[];
};

export type View = ChoicesView | ResultView;
export type ChoiceResult =
  | { accepted: true; view: View }
  | { accepted: false; code: string; view: View };

export function toView(payload: DeepReadonly<Payload> | null): View {
  if (isNodePayload(payload)) {
    return {
      kind: 'choices',
      nodeId: payload.nodeId,
      heading: payload.title ?? '',
      description: payload.description ?? '',
      choices: payload.edges.map(edge => ({
        edgeId: edge.id,
        label: edge.label ?? String(edge.id),
        enabled: edge.enabled !== false,
        availability: edge.availability ?? null,
        reason: edge.disabledReason ?? null,
      })),
    };
  }
  if (isTerminalPayload(payload)) {
    return {
      kind: 'result',
      nodeId: payload.nodeId,
      heading: payload.title ?? '',
      messages: payload.outputs.flatMap(output =>
        output.type === 'content' && typeof output.content === 'string'
          ? [output.content] : []),
      links: payload.outputs.flatMap(output =>
        (output.type === 'url' || output.type === 'redirect')
          && typeof output.url === 'string'
          ? [{ kind: output.type, label: output.label ?? output.url, url: output.url }]
          : []),
    };
  }
  throw new Error('No displayable session payload.');
}

// Application code: create one instance for one application-owned session.
export class SessionService {
  private session: Session | null = null;

  constructor(private readonly client: ExecKernelClient) {}

  get sessionId(): string | null {
    return this.session?.sessionId ?? null;
  }

  get view(): View {
    return toView(this.session?.currentPayload ?? null);
  }

  async start(context: Context): Promise<View> {
    this.session = await this.client.startSession(context);
    return this.view;
  }

  async resume(sessionId: string): Promise<View> {
    this.session = await this.client.restoreSession(sessionId);
    return this.view;
  }

  async choose(edgeId: number, context: Context = {}): Promise<ChoiceResult> {
    if (!this.session || !this.sessionId) throw new Error('Start or resume first.');
    try {
      await this.session.selectEdge(edgeId, context);
      return { accepted: true, view: this.view };
    } catch (error) {
      if (!(error instanceof ExecKernelError) || error.ekCode !== 'EK-RULE-403') {
        throw error;
      }
      // A known rejection: refresh the view; do not repeat the rejected choice.
      const view = await this.resume(this.sessionId);
      return { accepted: false, code: error.ekCode, view };
    }
  }
}

async function main(): Promise<void> {
  const baseUrl = process.env.EXECKERNEL_BASE_URL;
  const apiKey = process.env.EXECKERNEL_API_TOKEN;
  if (!baseUrl || !apiKey) {
    throw new Error('Set EXECKERNEL_BASE_URL and EXECKERNEL_API_TOKEN.');
  }
  const client = new ExecKernelClient({
    baseUrl,
    apiKey,
    flowId: process.env.EXECKERNEL_GRAPH_CODE || 'learning-path',
    lang: process.env.EXECKERNEL_LANG || 'en',
  });
  const service = new SessionService(client);
  try {
    const initial = await service.start({ practiceEnabled: false });
    // Deliberately submit a disabled choice to demonstrate rejection recovery.
    const rejected = await service.choose(102);
    const selected = await service.choose(101);
    const sessionId = service.sessionId;
    if (!sessionId) throw new Error('Missing session identifier.');
    const resumed = await service.resume(sessionId);
    console.log(JSON.stringify({ initial, rejected, selected, resumed }, null, 2));
  } finally {
    // Cleanup belongs to this demonstration, not to the reusable service.
    if (service.sessionId) await client.destroy(service.sessionId);
  }
}

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