/**
 * SOP AI Pipeline
 *
 * Orchestrates a 3-stage AI pipeline for generating a complete SOP.
 * Stage 1: SOP Identity (title, description, objective, scope, metadata)
 * Stage 2: SOP Steps (workflow with 5-8 steps)
 * Stage 3: SOP Strategy (internal notes, SEO, compliance)
 */

import { generateWithAI } from '../../utils/aiProvider';
import { parseJsonFromAI } from './parseJsonFromAI';
import {
  buildSopIdentityPrompt,
  buildSopStepsPrompt,
  buildSopStrategyPrompt,
  buildSopEnhancementPrompt,
  SopPipelineInputs,
  PromptResult,
} from './sopPrompts';

// ============================================
// TYPES
// ============================================

export interface SopPipelineResult {
  sop: Record<string, any>;
  steps: 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 SopPipeline {
  private inputs: SopPipelineInputs;
  private accumulated: Record<string, any>;
  private stepsAccumulated: 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: SopPipelineInputs, onProgress?: (progress: number, step: string) => void) {
    this.inputs = inputs;
    this.accumulated = { sop: {} };
    this.stepsAccumulated = [];
    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<SopPipelineResult> {
    // Stage 1: SOP Identity
    this.onProgress?.(5, 'Creating SOP identity...');
    await this.runStageWithRetry('sop-identity', () =>
      this.executeStage(
        buildSopIdentityPrompt(this.inputs),
        'identity'
      )
    );
    this.onProgress?.(35, 'SOP identity defined');

    // Stage 2: SOP Steps
    this.onProgress?.(40, 'Building SOP steps...');
    await this.runStageWithRetry('sop-steps', () =>
      this.executeStage(
        buildSopStepsPrompt(this.inputs, this.accumulated),
        'steps'
      )
    );
    this.onProgress?.(65, 'SOP steps generated');

    // Stage 3: SOP Strategy
    this.onProgress?.(70, 'Optimizing SOP strategy...');
    await this.runStageWithRetry('sop-strategy', () =>
      this.executeStage(
        buildSopStrategyPrompt(this.inputs, { ...this.accumulated, steps: this.stepsAccumulated }),
        'strategy'
      )
    );
    this.onProgress?.(95, 'Finalizing SOP');

    const overallConfidence = this.computeOverallConfidence();

    return {
      sop: this.accumulated,
      steps: this.stepsAccumulated,
      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(`[SOP-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(`[SOP-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(`[SOP-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 { sop: { ... } }
      if (parsed.sop && typeof parsed.sop === 'object') {
        this.deepMerge(this.accumulated.sop, parsed.sop);
      }
    } else if (stageName === 'steps') {
      // Stage 2 returns { steps: [...] }
      if (parsed.steps && Array.isArray(parsed.steps)) {
        this.stepsAccumulated = parsed.steps;
      }
    } else if (stageName === 'strategy') {
      // Stage 3 returns { sop: { internalNotes, metaTitle, metaDescription }, complianceNotes, optimizationTips }
      if (parsed.sop && typeof parsed.sop === 'object') {
        this.deepMerge(this.accumulated.sop, parsed.sop);
      }
    }
  }

  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] === '' || (Array.isArray(target[key]) && target[key].length === 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, steps: this.stepsAccumulated };
      const enhancePrompt = buildSopEnhancementPrompt(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.sop && typeof parsed.sop === 'object') {
          this.deepMerge(this.accumulated.sop, parsed.sop);
        }
        if (parsed.steps && Array.isArray(parsed.steps)) {
          this.stepsAccumulated = parsed.steps;
        }
        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(`[SOP-Pipeline] Enhancement for ${stageName} failed: ${error.message}`);
    }
  }

  // ============================================
  // CONFIDENCE ANALYSIS
  // ============================================

  private getLowConfidenceFields(stageName: string): string[] {
    const low: string[] = [];
    const stageCriticalFields: Record<string, string[]> = {
      'sop-identity': ['title', 'objective', 'scope'],
      'sop-steps': ['steps'],
      'sop-strategy': ['internalNotes'],
    };

    const criticalFields = stageCriticalFields[stageName] || [];
    for (const field of criticalFields) {
      if (stageName === 'sop-steps') {
        if (!Array.isArray(this.stepsAccumulated) || this.stepsAccumulated.length === 0) low.push(field);
      } else {
        if (!this.accumulated.sop[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);
  }
}