/**
 * Event Quick Generate AI Pipeline
 *
 * Generates a complete event with sessions from basic user inputs
 * (title, description, date, time, event type, event mode).
 */

import { generateWithAI } from '../../utils/aiProvider';
import { parseJsonFromAI } from './parseJsonFromAI';
import {
  buildEventIdentityPrompt,
  buildEventSessionPrompt,
  buildEventStrategyPrompt,
  buildEventEnhancementPrompt,
  EventPipelineInputs,
  PromptResult,
} from './eventPrompts';

// ============================================
// TYPES
// ============================================

export interface EventPipelineResult {
  event: Record<string, any>;
  sessions: Record<string, any>[];
  pipelineVersion: string;
  provider: string;
  aiModel: string;
  tokensUsed: number;
  inputTokens: number;
  outputTokens: number;
  processingTimeMs: number;
  latencyMs: number;
  finishReason: string | null;
  apiKeyMasked: string | null;
  overallConfidence: number;
  stageResults: StageResult[];
  errors: string[];
}

export interface StageResult {
  stage: string;
  success: boolean;
  provider?: string;
  aiModel?: string;
  tokensUsed?: number;
  error?: string;
  duration: number;
  enhanced?: boolean;
}

const PIPELINE_VERSION = '1.0';

// ============================================
// JSON PARSING UTILITIES
// ============================================

// ============================================
// PIPELINE CLASS
// ============================================

export class EventPipeline {
  private inputs: EventPipelineInputs;
  private eventAccumulated: Record<string, any>;
  private sessionsAccumulated: Record<string, any>[];
  private stageResults: StageResult[];
  private errors: string[];
  private totalTokens: number;
  private totalInputTokens: number;
  private totalOutputTokens: number;
  private totalLatencyMs: number;
  private lastFinishReason: string | null;
  private lastApiKeyMasked: string | null;
  private startTime: number;
  private lastProvider: string;
  private lastAiModel: string;
  private onProgress?: (progress: number, step: string) => void;

  constructor(inputs: EventPipelineInputs, onProgress?: (progress: number, step: string) => void) {
    this.inputs = inputs;
    this.eventAccumulated = {};
    this.sessionsAccumulated = [];
    this.stageResults = [];
    this.errors = [];
    this.totalTokens = 0;
    this.totalInputTokens = 0;
    this.totalOutputTokens = 0;
    this.totalLatencyMs = 0;
    this.lastFinishReason = null;
    this.lastApiKeyMasked = null;
    this.startTime = Date.now();
    this.lastProvider = 'unknown';
    this.lastAiModel = 'unknown';
    this.onProgress = onProgress;
  }

  async run(): Promise<EventPipelineResult> {
    // Stage 1: Event Identity
    this.onProgress?.(5, 'Creating event identity...');
    await this.runStageWithRetry('event-identity', () =>
      this.executeStage(buildEventIdentityPrompt(this.inputs), 'identity', 0)
    );
    this.onProgress?.(35, 'Event identity defined');

    // Stage 2: Session Structure
    this.onProgress?.(40, 'Building event sessions...');
    await this.runStageWithRetry('event-sessions', () =>
      this.executeStage(
        buildEventSessionPrompt(this.inputs, { event: this.eventAccumulated }),
        'sessions',
        1
      )
    );
    this.onProgress?.(65, 'Event sessions generated');

    // Stage 3: Strategy & SEO
    this.onProgress?.(70, 'Optimizing event strategy...');
    await this.runStageWithRetry('event-strategy', () =>
      this.executeStage(
        buildEventStrategyPrompt(this.inputs, { event: this.eventAccumulated, sessions: this.sessionsAccumulated }),
        'strategy',
        2
      )
    );
    this.onProgress?.(95, 'Finalizing event');

    const overallConfidence = this.computeOverallConfidence();

    return {
      event: this.eventAccumulated,
      sessions: this.sessionsAccumulated,
      pipelineVersion: PIPELINE_VERSION,
      provider: this.lastProvider,
      aiModel: this.lastAiModel,
      tokensUsed: this.totalTokens,
      inputTokens: this.totalInputTokens,
      outputTokens: this.totalOutputTokens,
      processingTimeMs: Date.now() - this.startTime,
      latencyMs: this.totalLatencyMs,
      overallConfidence,
      finishReason: this.lastFinishReason,
      apiKeyMasked: this.lastApiKeyMasked,
      stageResults: this.stageResults,
      errors: this.errors,
    };
  }

  // ============================================
  // STAGE EXECUTION
  // ============================================

  private async executeStage(promptConfig: PromptResult, stageName: string, stageIndex: number): Promise<void> {
    console.log(`[Event-Pipeline] Executing stage "${stageName}" with ${promptConfig.maxTokens} maxTokens`);

    const result = await generateWithAI(
      promptConfig.userPrompt,
      promptConfig.systemPrompt,
      promptConfig.maxTokens
    );

    this.lastProvider = result.provider;
    this.lastAiModel = result.model;
    this.totalTokens += result.tokenUsage?.totalTokens ?? 0;
    this.totalInputTokens += result.tokenUsage?.inputTokens ?? 0;
    this.totalOutputTokens += result.tokenUsage?.outputTokens ?? 0;
    if (result.latencyMs) this.totalLatencyMs += result.latencyMs;
    if (result.finishReason) this.lastFinishReason = result.finishReason;
    if (result.keyUsed) this.lastApiKeyMasked = result.keyUsed;

    console.log(`[Event-Pipeline] Stage "${stageName}" response received. Provider: ${result.provider}, Content length: ${result.content?.length || 0}`);

    const parsed = parseJsonFromAI(result.content);
    if (!parsed) {
      throw new Error(`AI response could not be parsed as JSON for stage: ${stageName}`);
    }

    // Extract event data
    if (parsed.event && typeof parsed.event === 'object' && !Array.isArray(parsed.event)) {
      this.mergeEvent(parsed.event);
    }

    // Extract sessions
    if (parsed.sessions && Array.isArray(parsed.sessions)) {
      for (const session of parsed.sessions) {
        if (session && typeof session === 'object' && session.title) {
          this.mergeIntoSessions(session);
        }
      }
    }
  }

  private async runStageWithRetry(stageName: string, stageFn: () => Promise<void>): Promise<void> {
    const stageStart = Date.now();

    try {
      await stageFn();
      this.stageResults.push({
        stage: stageName,
        success: true,
        provider: this.lastProvider,
        aiModel: this.lastAiModel,
        duration: Date.now() - stageStart,
      });
    } catch (error: any) {
      this.errors.push(`Stage ${stageName} failed: ${error.message}`);
      this.stageResults.push({
        stage: stageName,
        success: false,
        error: error.message,
        duration: Date.now() - stageStart,
      });
      return;
    }

    const lowFields = this.getLowConfidenceFields(stageName);
    if (lowFields.length > 0) {
      await this.enhanceStage(stageName, lowFields);
    }
  }

  private async enhanceStage(stageName: string, lowConfidenceFields: string[]): Promise<void> {
    const enhanceStart = Date.now();

    try {
      const stageOutput = { event: this.eventAccumulated, sessions: this.sessionsAccumulated };
      const enhancePrompt = buildEventEnhancementPrompt(stageName, stageOutput, lowConfidenceFields);

      const result = await generateWithAI(
        enhancePrompt.userPrompt,
        enhancePrompt.systemPrompt,
        enhancePrompt.maxTokens
      );

      this.totalTokens += result.tokenUsage?.totalTokens ?? 0;
      this.totalInputTokens += result.tokenUsage?.inputTokens ?? 0;
      this.totalOutputTokens += result.tokenUsage?.outputTokens ?? 0;
      if (result.latencyMs) this.totalLatencyMs += result.latencyMs;
      if (result.finishReason) this.lastFinishReason = result.finishReason;
      if (result.keyUsed) this.lastApiKeyMasked = result.keyUsed;
      const parsed = parseJsonFromAI(result.content);
      if (parsed) {
        if (parsed.event) this.mergeEvent(parsed.event);
        if (parsed.sessions && Array.isArray(parsed.sessions)) {
          for (const session of parsed.sessions) {
            if (session && typeof session === 'object') this.mergeIntoSessions(session);
          }
        }
        this.stageResults.push({
          stage: `${stageName}-enhancement`,
          success: true,
          provider: result.provider,
          aiModel: result.model,
          duration: Date.now() - enhanceStart,
          enhanced: true,
        });
      }
    } catch (error: any) {
      console.warn(`[Event-Pipeline] Enhancement for ${stageName} failed: ${error.message}`);
    }
  }

  // ============================================
  // RESULT MERGING
  // ============================================

  private mergeEvent(parsed: Record<string, any>): void {
    if (!parsed || typeof parsed !== 'object') return;
    for (const [key, value] of Object.entries(parsed)) {
      if (key === 'sessions') continue;
      if (value !== null && value !== undefined) {
        const existing = this.eventAccumulated[key];
        if (existing === undefined || existing === null || existing === '' || (Array.isArray(existing) && existing.length === 0)) {
          this.eventAccumulated[key] = value;
        } else if (Array.isArray(value) && value.length > 0 && Array.isArray(existing) && value.length > existing.length) {
          this.eventAccumulated[key] = value;
        }
      }
    }
  }

  private mergeIntoSessions(session: Record<string, any>): void {
    if (!session || typeof session !== 'object') return;
    const existingIdx = this.sessionsAccumulated.findIndex(s => s.title && s.title === session.title);
    if (existingIdx >= 0) {
      const target = this.sessionsAccumulated[existingIdx];
      for (const [key, value] of Object.entries(session)) {
        if (value !== null && value !== undefined) {
          const existing = target[key];
          if (existing === undefined || existing === null || existing === '' || (Array.isArray(existing) && existing.length === 0)) {
            target[key] = value;
          }
        }
      }
    } else {
      this.sessionsAccumulated.push({ ...session });
    }
  }

  // ============================================
  // CONFIDENCE ANALYSIS
  // ============================================

  private getLowConfidenceFields(stageName: string): string[] {
    const low: string[] = [];

    if (stageName === 'event-identity') {
      if (!this.eventAccumulated.shortDescription) low.push('shortDescription');
      if (!this.eventAccumulated.detailedDescription) low.push('detailedDescription');
      if (!this.eventAccumulated.objectives?.length) low.push('objectives');
    } else if (stageName === 'event-sessions') {
      const missingSessions = this.sessionsAccumulated.filter(s => !s.title).length;
      if (missingSessions > 0) low.push('session.title');
    }

    return low;
  }

  private computeOverallConfidence(): number {
    const successCount = this.stageResults.filter(s => s.success && !s.enhanced).length;
    const successRate = successCount / 3;
    return Math.round(successRate * 100);
  }
}