/**
 * Loyalty Programme AI Pipeline
 *
 * Orchestrates a 3-stage AI pipeline for generating a complete loyalty programme.
 * Stage 1: Programme Identity (name, description, type, settings)
 * Stage 2: Programme Structure (tiers, earn rules, redeem rules, rewards, notifications)
 * Stage 3: Programme Optimization (terms, branding, strategy)
 */

import { generateWithAI } from '../../utils/aiProvider';
import { parseJsonFromAI } from './parseJsonFromAI';
import {
  buildLoyaltyIdentityPrompt,
  buildLoyaltyStructurePrompt,
  buildLoyaltyStrategyPrompt,
  buildLoyaltyEnhancementPrompt,
  LoyaltyPipelineInputs,
  PromptResult,
} from './loyaltyPrompts';

// ============================================
// TYPES
// ============================================

export interface LoyaltyPipelineResult {
  programme: 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 LoyaltyPipeline {
  private inputs: LoyaltyPipelineInputs;
  private accumulated: 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: LoyaltyPipelineInputs, onProgress?: (progress: number, step: string) => void) {
    this.inputs = inputs;
    this.accumulated = { programme: {} };
    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<LoyaltyPipelineResult> {
    // Stage 1: Programme Identity
    this.onProgress?.(5, 'Creating programme identity...');
    await this.runStageWithRetry('loyalty-identity', () =>
      this.executeStage(
        buildLoyaltyIdentityPrompt(this.inputs),
        'identity'
      )
    );
    this.onProgress?.(35, 'Programme identity defined');

    // Stage 2: Programme Structure
    this.onProgress?.(40, 'Building programme structure...');
    await this.runStageWithRetry('loyalty-structure', () =>
      this.executeStage(
        buildLoyaltyStructurePrompt(this.inputs, this.accumulated),
        'structure'
      )
    );
    this.onProgress?.(65, 'Programme structure generated');

    // Stage 3: Programme Optimization
    this.onProgress?.(70, 'Optimizing programme...');
    await this.runStageWithRetry('loyalty-strategy', () =>
      this.executeStage(
        buildLoyaltyStrategyPrompt(this.inputs, this.accumulated),
        'strategy'
      )
    );
    this.onProgress?.(95, 'Finalizing programme');

    const overallConfidence = this.computeOverallConfidence();

    return {
      programme: this.accumulated,
      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): Promise<void> {
    console.log(`[Loyalty-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(`[Loyalty-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(`[Loyalty-Pipeline] Stage "${stageName}": JSON parsing failed, extracted ${Object.keys(extracted).length} fields`);
        this.mergeStageResult(stageName, extracted);
        return;
      }
      throw new Error(`AI response could not be parsed as JSON for stage: ${stageName}`);
    }

    this.mergeStageResult(stageName, parsed);
  }

  private mergeStageResult(stageName: string, parsed: Record<string, any>): void {
    if (stageName === 'identity') {
      // Stage 1 returns { programme: { ... } }
      if (parsed.programme && typeof parsed.programme === 'object') {
        this.deepMerge(this.accumulated.programme, parsed.programme);
      }
    } else if (stageName === 'structure') {
      // Stage 2 returns { tiers, earnRules, redeemRules, rewards, notifications }
      for (const key of ['tiers', 'earnRules', 'redeemRules', 'rewards', 'notifications']) {
        if (parsed[key] && Array.isArray(parsed[key])) {
          (this.accumulated as any)[key] = parsed[key];
        }
      }
    } else if (stageName === 'strategy') {
      // Stage 3 returns { programme: { termsConditions, privacyPolicy, primaryColour, secondaryColour }, bestPractices, optimizationTips }
      if (parsed.programme && typeof parsed.programme === 'object') {
        this.deepMerge(this.accumulated.programme, parsed.programme);
      }
    }
  }

  private deepMerge(target: Record<string, any>, source: Record<string, any>): void {
    for (const [key, value] of Object.entries(source)) {
      if (value === null || value === undefined) continue;
      if (
        typeof value === 'object' && !Array.isArray(value) &&
        typeof target[key] === 'object' && !Array.isArray(target[key]) && target[key] !== null
      ) {
        this.deepMerge(target[key], value);
      } else if (target[key] === undefined || target[key] === null || target[key] === '' || target[key] === 0) {
        target[key] = value;
      }
    }
  }

  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 = this.accumulated;
      const enhancePrompt = buildLoyaltyEnhancementPrompt(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.programme && typeof parsed.programme === 'object') {
          this.deepMerge(this.accumulated.programme, parsed.programme);
        }
        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(`[Loyalty-Pipeline] Enhancement for ${stageName} failed: ${error.message}`);
    }
  }

  // ============================================
  // CONFIDENCE ANALYSIS
  // ============================================

  private getLowConfidenceFields(stageName: string): string[] {
    const low: string[] = [];
    const stageCriticalFields: Record<string, string[]> = {
      'loyalty-identity': ['name', 'type', 'baseEarnRate'],
      'loyalty-structure': ['tiers', 'earnRules', 'redeemRules'],
      'loyalty-strategy': ['termsConditions'],
    };

    const criticalFields = stageCriticalFields[stageName] || [];
    for (const field of criticalFields) {
      if (stageName === 'loyalty-structure') {
        const arr = (this.accumulated as any)[field];
        if (!Array.isArray(arr) || arr.length === 0) low.push(field);
      } else {
        if (!this.accumulated.programme[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);
  }
}