/**
 * Testimonial AI Pipeline
 *
 * Orchestrates a 3-stage AI analysis pipeline for testimonial generation.
 * Generates multiple (default 5) diverse testimonials in one pass.
 * Uses company context, ICP data, and brand strategy as seed input.
 */

import { generateWithAI } from '../../utils/aiProvider';
import { parseJsonFromAI } from './parseJsonFromAI';
import {
  buildTestimonialIdentityPrompt,
  buildTestimonialContentPrompt,
  buildTestimonialQualityPrompt,
  buildTestimonialEnhancementPrompt,
  TestimonialPipelineInputs,
  PromptResult,
} from './testimonialPrompts';

// ============================================
// TYPES
// ============================================

export interface TestimonialPipelineResult {
  testimonials: Record<string, any>[];
  pipelineVersion: string;
  provider: string;
  aiModel: string;
  tokensUsed: number;
  inputTokens: number;
  outputTokens: number;
  processingTimeMs: number;
  latencyMs: number;
  overallConfidence: number;
  fieldConfidences: Record<string, number>;
  finishReason: string | null;
  apiKeyMasked: string | null;
  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 = '2.0';
const CONFIDENCE_THRESHOLD = 60;

// ============================================
// JSON PARSING UTILITY
// ============================================

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;
    }
  }

  const nestedObjRegex = /"(\w+)":\s*(\{[^}]*\})/g;
  while ((match = nestedObjRegex.exec(content)) !== null) {
    const [, key, objStr] = match;
    try {
      result[key] = JSON.parse(objStr);
    } catch {
      // Skip unparseable nested objects
    }
  }

  return result;
}

/**
 * Extract testimonial array from parsed response.
 * Handles both array responses and { testimonials: [...] } wrapper format.
 */
function extractTestimonialArray(parsed: Record<string, any>): Record<string, any>[] {
  if (Array.isArray(parsed)) {
    return parsed;
  }
  if (parsed.testimonials && Array.isArray(parsed.testimonials)) {
    return parsed.testimonials;
  }
  // Single testimonial format (fallback) — wrap in array
  return [parsed];
}

// ============================================
// PIPELINE CLASS
// ============================================

export class TestimonialPipeline {
  private inputs: TestimonialPipelineInputs;
  private testimonialAccumulated: 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 targetCount: number;
  private onProgress?: (progress: number, step: string) => void;

  constructor(inputs: TestimonialPipelineInputs, onProgress?: (progress: number, step: string) => void) {
    this.inputs = inputs;
    this.targetCount = inputs.targetCount || 5;
    this.testimonialAccumulated = Array.from({ length: this.targetCount }, () => ({}));
    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<TestimonialPipelineResult> {
    // Stage 1: Generate identities for all testimonials
    this.onProgress?.(5, 'Creating testimonial identities...');
    await this.runStageWithRetry('testimonial-identity', () =>
      this.executeIdentityStage()
    );
    this.onProgress?.(35, 'Identities defined');

    // Stage 2: Generate content for all testimonials
    this.onProgress?.(40, 'Generating testimonial content...');
    await this.runStageWithRetry('testimonial-content', () =>
      this.executeContentStage()
    );
    this.onProgress?.(65, 'Content generated');

    // Stage 3: Generate quality scores for all testimonials
    this.onProgress?.(70, 'Evaluating quality & authenticity...');
    await this.runStageWithRetry('testimonial-quality', () =>
      this.executeQualityStage()
    );
    this.onProgress?.(95, 'Finalizing testimonials');

    const overallConfidence = this.computeOverallConfidence();
    const fieldConfidences = this.extractFieldConfidences();

    return {
      testimonials: this.testimonialAccumulated,
      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,
      fieldConfidences,
      finishReason: this.lastFinishReason,
      apiKeyMasked: this.lastApiKeyMasked,
      stageResults: this.stageResults,
      errors: this.errors,
    };
  }

  // ============================================
  // STAGE EXECUTION
  // ============================================

  private async executeIdentityStage(): Promise<void> {
    console.log(`[Testimonial-Pipeline] Executing identity stage for ${this.targetCount} testimonials`);
    const promptConfig = buildTestimonialIdentityPrompt(this.inputs, this.targetCount);
    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(`[Testimonial-Pipeline] Identity stage response received. Provider: ${result.provider}, Model: ${result.model}, Content length: ${result.content?.length || 0}`);
    console.log(`[Testimonial-Pipeline] Identity stage raw response (first 500 chars): ${result.content?.substring(0, 500)}`);

    const parsed = parseJsonFromAI(result.content);
    if (!parsed) {
      const extracted = extractFieldsFromRawContent(result.content);
      if (Object.keys(extracted).length > 0) {
        console.warn('[Testimonial-Pipeline] Identity stage: JSON parsing failed, extracted fields as single testimonial');
        this.mergeIntoTestimonial(0, extracted);
        return;
      }
      throw new Error('AI response could not be parsed as JSON for identity stage');
    }

    const testimonials = extractTestimonialArray(parsed);
    console.log(`[Testimonial-Pipeline] Identity stage: parsed ${testimonials.length} testimonials`);

    for (let i = 0; i < testimonials.length && i < this.targetCount; i++) {
      this.mergeIntoTestimonial(i, testimonials[i]);
    }

    // If we got fewer than targetCount, fill remaining slots with variants
    while (this.testimonialAccumulated.filter(t => Object.keys(t).length > 0).length < this.targetCount && testimonials.length > 0) {
      const existingCount = this.testimonialAccumulated.filter(t => Object.keys(t).length > 0).length;
      if (existingCount >= this.targetCount) break;
      const lastT = testimonials[testimonials.length - 1];
      const variant = { ...lastT, customerName: `${lastT.customerName || 'Customer'} ${existingCount + 1}`, headline: `${lastT.headline || 'Great experience'} (Variant ${existingCount + 1})` };
      this.mergeIntoTestimonial(existingCount, variant);
    }
  }

  private async executeContentStage(): Promise<void> {
    console.log(`[Testimonial-Pipeline] Executing content stage for ${this.targetCount} testimonials`);
    const identities = this.testimonialAccumulated.map(t => ({ ...t }));
    const promptConfig = buildTestimonialContentPrompt(this.inputs, identities);
    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(`[Testimonial-Pipeline] Content stage response received. Provider: ${result.provider}, Model: ${result.model}, 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('[Testimonial-Pipeline] Content stage: JSON parsing failed, extracted fields as single testimonial');
        this.mergeIntoTestimonial(0, extracted);
        return;
      }
      throw new Error('AI response could not be parsed as JSON for content stage');
    }

    const testimonials = extractTestimonialArray(parsed);
    console.log(`[Testimonial-Pipeline] Content stage: parsed ${testimonials.length} testimonials`);

    for (let i = 0; i < testimonials.length && i < this.targetCount; i++) {
      this.mergeIntoTestimonial(i, testimonials[i]);
    }
  }

  private async executeQualityStage(): Promise<void> {
    console.log(`[Testimonial-Pipeline] Executing quality stage for ${this.targetCount} testimonials`);
    const partials = this.testimonialAccumulated.map(t => ({ ...t }));
    const promptConfig = buildTestimonialQualityPrompt(this.inputs, partials);
    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(`[Testimonial-Pipeline] Quality stage response received. Provider: ${result.provider}, Model: ${result.model}, 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('[Testimonial-Pipeline] Quality stage: JSON parsing failed, extracted fields as single testimonial');
        this.mergeIntoTestimonial(0, extracted);
        return;
      }
      throw new Error('AI response could not be parsed as JSON for quality stage');
    }

    const testimonials = extractTestimonialArray(parsed);
    console.log(`[Testimonial-Pipeline] Quality stage: parsed ${testimonials.length} testimonials`);

    for (let i = 0; i < testimonials.length && i < this.targetCount; i++) {
      this.mergeIntoTestimonial(i, testimonials[i]);
    }
  }

  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;
    }

    // Enhancement retry for low-confidence fields
    const lowConfidenceFields = this.getLowConfidenceFields(stageName);
    if (lowConfidenceFields.length > 0) {
      await this.enhanceStage(stageName, lowConfidenceFields);
    }
  }

  // ============================================
  // ENHANCEMENT RETRY
  // ============================================

  private async enhanceStage(stageName: string, lowConfidenceFields: string[]): Promise<void> {
    const enhanceStart = Date.now();

    try {
      const mergedOutput = this.getMergedOutput();
      const enhancePrompt = buildTestimonialEnhancementPrompt(stageName, mergedOutput, 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) {
        const testimonials = extractTestimonialArray(parsed);
        if (testimonials.length > 0) {
          this.mergeIntoTestimonial(0, testimonials[0]);
        } else {
          this.mergeIntoTestimonial(0, parsed);
        }
        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(`[Testimonial-Pipeline] Enhancement for ${stageName} failed: ${error.message}`);
    }
  }

  // ============================================
  // RESULT MERGING
  // ============================================

  private mergeIntoTestimonial(index: number, parsed: Record<string, any>): void {
    for (const [key, value] of Object.entries(parsed)) {
      if (value !== null && value !== undefined) {
        this.testimonialAccumulated[index][key] = value;
      }
    }
  }

  private getMergedOutput(): Record<string, any> {
    const merged: Record<string, any> = {};
    for (let i = 0; i < this.testimonialAccumulated.length; i++) {
      const t = this.testimonialAccumulated[i];
      if (Object.keys(t).length === 0) continue;
      const activeCount = this.testimonialAccumulated.filter(t => Object.keys(t).length > 0).length;
      if (activeCount === 1) {
        Object.assign(merged, t);
      } else {
        for (const [key, value] of Object.entries(t)) {
          merged[`t${i + 1}_${key}`] = value;
        }
      }
    }
    return merged;
  }

  // ============================================
  // CONFIDENCE ANALYSIS
  // ============================================

  private getLowConfidenceFields(stageName: string): string[] {
    const low: string[] = [];
    const stageCriticalFields: Record<string, string[]> = {
      'testimonial-identity': ['customerName', 'headline', 'type'],
      'testimonial-content': ['fullTestimonial', 'story'],
      'testimonial-quality': ['authenticityScore', 'trustScore'],
    };

    const criticalFields = stageCriticalFields[stageName] || [];
    for (const field of criticalFields) {
      const allEmpty = this.testimonialAccumulated.every(t => !t[field] || t[field] === '');
      if (allEmpty && !low.includes(field)) {
        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);
  }

  private extractFieldConfidences(): Record<string, number> {
    const confidences: Record<string, number> = {};
    const overall = this.computeOverallConfidence();

    const allFields = [
      'customerName', 'headline', 'type',
      'fullTestimonial', 'story',
      'authenticityScore', 'trustScore',
    ];

    for (const field of allFields) {
      const anyHas = this.testimonialAccumulated.some(t => t[field]);
      if (anyHas) {
        confidences[field] = overall;
      }
    }

    return confidences;
  }
}