/**
 * Persona (Buyer Persona) AI Pipeline
 *
 * Orchestrates a 3-stage AI analysis pipeline for Persona generation.
 * Uses company context and ICP data as seed input.
 * Follows the same pattern as ICPPipeline.
 */

import { generateWithAI } from '../../utils/aiProvider';
import { parseJsonFromAI } from './parseJsonFromAI';
import {
  buildPersonaDemographicsPrompt,
  buildPersonaPsychographicsPrompt,
  buildPersonaBuyingPrompt,
  buildPersonaEnhancementPrompt,
  PersonaPipelineInputs,
  PromptResult,
} from './personaPrompts';

// ============================================
// TYPES
// ============================================

export interface PersonaPipelineResult {
  analysis: 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;
  fieldConfidences: Record<string, 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 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;
}

// ============================================
// PIPELINE CLASS
// ============================================

export class PersonaPipeline {
  private inputs: PersonaPipelineInputs;
  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;

  constructor(inputs: PersonaPipelineInputs) {
    this.inputs = inputs;
    this.accumulated = {};
    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';
  }

  async run(): Promise<PersonaPipelineResult> {
    // Stage 1: Demographics & Professional
    await this.runStageWithRetry('demographics', () =>
      this.executeStage(buildPersonaDemographicsPrompt(this.inputs), 'name')
    );

    // Stage 2: Psychographics & Goals
    await this.runStageWithRetry('psychographics', () =>
      this.executeStage(buildPersonaPsychographicsPrompt(this.inputs, this.accumulated), 'goals')
    );

    // Stage 3: Behavioural & Buying
    await this.runStageWithRetry('buying', () =>
      this.executeStage(buildPersonaBuyingPrompt(this.inputs, this.accumulated), 'decisionMakingStyle')
    );

    const overallConfidence = this.computeOverallConfidence();
    const fieldConfidences = this.extractFieldConfidences();

    return {
      analysis: 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,
      finishReason: this.lastFinishReason,
      apiKeyMasked: this.lastApiKeyMasked,
      overallConfidence,
      fieldConfidences,
      stageResults: this.stageResults,
      errors: this.errors,
    };
  }

  // ============================================
  // STAGE EXECUTION
  // ============================================

  private async executeStage(promptConfig: PromptResult, primaryField: string): Promise<void> {
    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;

    const parsed = parseJsonFromAI(result.content);
    if (!parsed) {
      const extracted = extractFieldsFromRawContent(result.content);
      if (Object.keys(extracted).length > 0) {
        console.warn(`[Persona-Pipeline] Stage "${primaryField}": JSON parsing failed, extracted ${Object.keys(extracted).length} fields`);
        this.mergeStageResult(extracted);
        return;
      }
      throw new Error(`AI response could not be parsed as JSON for stage: ${primaryField}`);
    }

    this.mergeStageResult(parsed);
  }

  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 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 stageOutput = this.getStageOutput(stageName);
      const enhancePrompt = buildPersonaEnhancementPrompt(stageName, stageOutput, lowConfidenceFields, this.inputs);

      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) {
        this.mergeStageResult(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(`[Persona-Pipeline] Enhancement for ${stageName} failed: ${error.message}`);
    }
  }

  // ============================================
  // RESULT MERGING
  // ============================================

  private mergeStageResult(parsed: Record<string, any>): void {
    for (const [key, value] of Object.entries(parsed)) {
      if (value !== null && value !== undefined) {
        this.accumulated[key] = value;
      }
    }
  }

  // ============================================
  // CONFIDENCE ANALYSIS
  // ============================================

  private getLowConfidenceFields(stageName: string): string[] {
    const low: string[] = [];
    const stageCriticalFields: Record<string, string[]> = {
      'demographics': ['name', 'jobTitle', 'seniorityLevel'],
      'psychographics': ['goals', 'painPoints'],
      'buying': ['decisionMakingStyle', 'buyingRole'],
    };

    const criticalFields = stageCriticalFields[stageName] || [];
    for (const field of criticalFields) {
      if (!this.accumulated[field] || this.accumulated[field] === '') {
        if (!low.includes(field)) {
          low.push(field);
        }
      }
    }

    return low;
  }

  private getStageOutput(stageName: string): Record<string, any> {
    const stageFieldMap: Record<string, string[]> = {
      'demographics': ['name', 'ageRange', 'gender', 'jobTitle', 'seniorityLevel', 'department', 'industry', 'experience', 'skills', 'toolsUsed', 'certifications'],
      'psychographics': ['bio', 'quote', 'goals', 'painPoints', 'motivations', 'values', 'fears'],
      'buying': ['decisionMakingStyle', 'researchHabits', 'contentPreferences', 'communicationChannel', 'dailyChallenges', 'successMetrics', 'kpi', 'budgetAuthority', 'influenceLevel', 'buyingRole', 'objections', 'expectedBudget', 'spendingAuthority', 'budgetOwnership', 'purchaseApprovalLevel'],
    };

    const fields = stageFieldMap[stageName] || [];
    const output: Record<string, any> = {};
    for (const field of fields) {
      if (this.accumulated[field] !== undefined) {
        output[field] = this.accumulated[field];
      }
    }
    return output;
  }

  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 = [
      'name', 'jobTitle', 'seniorityLevel', 'department', 'bio', 'quote',
      'goals', 'painPoints', 'motivations', 'decisionMakingStyle',
      'buyingRole', 'budgetAuthority', 'influenceLevel',
      'expectedBudget', 'spendingAuthority', 'budgetOwnership', 'purchaseApprovalLevel',
    ];

    for (const field of allFields) {
      if (this.accumulated[field]) {
        confidences[field] = overall;
      }
    }

    return confidences;
  }
}