import {routePrompt} from './promptRouter';
import {generateReportResponse} from './responseGenerator';
import type {ChatMessage, MessagePart, ReportPart} from '@/features/loyaly-ai/types/chat';

const CHUNK_DELAY_MS = 25;

function sleep(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

export async function* streamDynamicAiResponse(
  prompt: string,
  _history: ChatMessage[],
  signal?: AbortSignal
): AsyncGenerator<MessagePart, void, undefined> {
  // 1. Brief thinking delay
  await sleep(350);
  if (signal?.aborted) return;

  // 2. Classify intent & extract entities
  const route = routePrompt(prompt);
  const fullReport = generateReportResponse(route);

  // 3. Progressive streaming simulation (Summary -> KPIs -> Charts -> Tables -> Insights -> Actions)
  // Step A: Stream Summary text first
  if (fullReport.summary) {
    const words = fullReport.summary.split(' ');
    let textChunk = '';
    for (let i = 0; i < words.length; i += 3) {
      if (signal?.aborted) return;
      textChunk += (textChunk ? ' ' : '') + words.slice(i, i + 3).join(' ');
      yield {
        type: 'report',
        title: fullReport.title,
        summary: textChunk,
      } as ReportPart;
      await sleep(CHUNK_DELAY_MS);
    }
  }

  // Step B: Stream KPI cards
  if (fullReport.kpis && fullReport.kpis.length > 0) {
    if (signal?.aborted) return;
    yield {
      type: 'report',
      title: fullReport.title,
      summary: fullReport.summary,
      kpis: fullReport.kpis,
    } as ReportPart;
    await sleep(200);
  }

  // Step C: Stream Charts
  if (fullReport.charts && fullReport.charts.length > 0) {
    if (signal?.aborted) return;
    yield {
      type: 'report',
      title: fullReport.title,
      summary: fullReport.summary,
      kpis: fullReport.kpis,
      charts: fullReport.charts,
    } as ReportPart;
    await sleep(200);
  }

  // Step D: Stream Tables
  if (fullReport.tables && fullReport.tables.length > 0) {
    if (signal?.aborted) return;
    yield {
      type: 'report',
      title: fullReport.title,
      summary: fullReport.summary,
      kpis: fullReport.kpis,
      charts: fullReport.charts,
      tables: fullReport.tables,
    } as ReportPart;
    await sleep(200);
  }

  // Step E: Stream Insights & Actions (Final complete report)
  if (signal?.aborted) return;
  yield fullReport;
}
