/**
 * Email Template AI Pipeline
 *
 * Orchestrates a 3-stage AI pipeline for generating email templates.
 * Uses company context + books/courses/events as seed data.
 */

import { generateWithAI } from '../../utils/aiProvider';
import { parseJsonFromAI } from './parseJsonFromAI';
import {
  buildEmailIdentityPrompt,
  buildEmailContentPrompt,
  buildEmailStrategyPrompt,
  buildEmailEnhancementPrompt,
  EmailPipelineInputs,
  PromptResult,
} from './emailPrompts';

// ============================================
// TYPES
// ============================================

export interface EmailPipelineResult {
  templates: 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
// ============================================

function extractFieldsFromRawContent(content: string): Record<string, any> {
  const result: Record<string, any> = {};
  if (!content || typeof content !== 'string') return result;

  const stringPairRegex = /"(\w+)":\s*"((?:[^"\\]|\\.)*)"/g;
  let match;
  while ((match = stringPairRegex.exec(content)) !== null) {
    const [, key, value] = match;
    result[key] = value.replace(/\\"/g, '"').replace(/\\n/g, '\n');
  }

  const arrayPairRegex = /"(\w+)":\s*\[((?:\s*"(?:[^"\\]|\\.)*"\s*,?\s*)+)\]/g;
  while ((match = arrayPairRegex.exec(content)) !== null) {
    const [, key, arrayContent] = match;
    const values = [...arrayContent.matchAll(/"((?:[^"\\]|\\.)*)"/g)].map(m => m[1]);
    if (values.length > 0) {
      result[key] = values;
    }
  }

  return result;
}

// ============================================
// PIPELINE CLASS
// ============================================

export class EmailPipeline {
  private inputs: EmailPipelineInputs;
  private templatesAccumulated: 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: EmailPipelineInputs, onProgress?: (progress: number, step: string) => void) {
    this.inputs = inputs;
    this.templatesAccumulated = new Array(inputs.targetCount).fill(null).map(() => ({}));
    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<EmailPipelineResult> {
    // Stage 1: Template Identity
    this.onProgress?.(5, 'Creating template identity...');
    await this.runStageWithRetry('email-identity', () =>
      this.executeStage(
        buildEmailIdentityPrompt(this.inputs),
        'identity',
        0
      )
    );
    this.onProgress?.(35, 'Template identity defined');

    // Stage 2: Email Content & Copy
    this.onProgress?.(40, 'Generating email content...');
    await this.runStageWithRetry('email-content', () =>
      this.executeStage(
        buildEmailContentPrompt(this.inputs, { templates: this.templatesAccumulated }),
        'content',
        1
      )
    );
    this.onProgress?.(65, 'Email content generated');

    // Stage 3: Strategy & Optimization
    this.onProgress?.(70, 'Optimizing email strategy...');
    await this.runStageWithRetry('email-strategy', () =>
      this.executeStage(
        buildEmailStrategyPrompt(this.inputs, { templates: this.templatesAccumulated }),
        'strategy',
        2
      )
    );
    this.onProgress?.(95, 'Finalizing templates');

    const overallConfidence = this.computeOverallConfidence();

    return {
      templates: this.templatesAccumulated,
      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(`[Email-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(`[Email-Pipeline] Stage "${stageName}" response received. Provider: ${result.provider}, Content length: ${result.content?.length || 0}`);

    const parsed = parseJsonFromAI(result.content);
    if (!parsed) {
      const extracted = extractFieldsFromRawContent(result.content);
      if (Object.keys(extracted).length > 0) {
        console.warn(`[Email-Pipeline] Stage "${stageName}": JSON parsing failed, extracted ${Object.keys(extracted).length} fields`);
        return;
      }
      throw new Error(`AI response could not be parsed as JSON for stage: ${stageName}`);
    }

    // Extract templates array
    if (parsed.templates && Array.isArray(parsed.templates)) {
      for (let i = 0; i < parsed.templates.length; i++) {
        const tmpl = parsed.templates[i];
        if (tmpl && typeof tmpl === 'object' && (tmpl.name || tmpl.subjectLine)) {
          this.mergeIntoTemplates(i, tmpl);
        }
      }
    }
  }

  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);
    }
  }

  // ============================================
  // ENHANCEMENT RETRY
  // ============================================

  private async enhanceStage(stageName: string, lowConfidenceFields: string[]): Promise<void> {
    const enhanceStart = Date.now();

    try {
      const stageOutput = { templates: this.templatesAccumulated };
      const enhancePrompt = buildEmailEnhancementPrompt(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.templates && Array.isArray(parsed.templates)) {
          for (let i = 0; i < parsed.templates.length; i++) {
            const tmpl = parsed.templates[i];
            if (tmpl && typeof tmpl === 'object') this.mergeIntoTemplates(i, tmpl);
          }
        }
        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(`[Email-Pipeline] Enhancement for ${stageName} failed: ${error.message}`);
    }
  }

  // ============================================
  // RESULT MERGING
  // ============================================

  private mergeIntoTemplates(index: number, tmpl: Record<string, any>): void {
    if (!tmpl || typeof tmpl !== 'object') return;
    if (index < 0 || index >= this.templatesAccumulated.length) {
      // If AI returns more templates than pre-allocated, push them
      this.templatesAccumulated.push({ ...tmpl });
      return;
    }
    const target = this.templatesAccumulated[index];
    for (const [key, value] of Object.entries(tmpl)) {
      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 if (key === 'body' && typeof value === 'string' && value.length > (existing?.length || 0)) {
          target[key] = value;
        }
      }
    }
  }

  // ============================================
  // CONFIDENCE ANALYSIS
  // ============================================

  private getLowConfidenceFields(stageName: string): string[] {
    const low: string[] = [];
    const stageCriticalFields: Record<string, string[]> = {
      'email-identity': ['name', 'type', 'subjectLine'],
      'email-content': ['body', 'ctaText'],
      'email-strategy': ['status'],
    };

    const criticalFields = stageCriticalFields[stageName] || [];
    for (const field of criticalFields) {
      const missingTemplates = this.templatesAccumulated.filter(t => !t[field]).length;
      if (missingTemplates > Math.floor(this.inputs.targetCount / 2)) low.push(field);
    }

    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);
  }
}