/**
 * Website Planner AI Pipeline
 *
 * Orchestrates a 3-stage AI analysis pipeline for website planner generation.
 * Uses company context, ICP data, and brand strategy as seed input.
 * Follows the same pattern as Competitor pipeline.
 */

import { generateWithAI } from '../../utils/aiProvider';
import { parseJsonFromAI } from './parseJsonFromAI';
import {
  buildWebsiteCorePrompt,
  buildStructurePrompt,
  buildFeaturesSeoPrompt,
  buildWebsitePlannerEnhancementPrompt,
  WebsitePlannerPipelineInputs,
  PromptResult,
} from './websitePlannerPrompts';

// ============================================
// TYPES
// ============================================

export interface WebsitePlannerPipelineResult {
  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';
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;
}

// ============================================
// PIPELINE CLASS
// ============================================

export class WebsitePlannerPipeline {
  private inputs: WebsitePlannerPipelineInputs;
  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: WebsitePlannerPipelineInputs, onProgress?: (progress: number, step: string) => void) {
    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';
    this.onProgress = onProgress;
  }

  async run(): Promise<WebsitePlannerPipelineResult> {
    // Stage 1: Website Core & Strategy
    this.onProgress?.(5, 'Analyzing business profile...');
    await this.runStageWithRetry('website-core', () =>
      this.executeStage(buildWebsiteCorePrompt(this.inputs), 'websiteType')
    );
    this.onProgress?.(35, 'Core strategy generated');

    // Stage 2: Sections & Pages
    this.onProgress?.(40, 'Designing website structure...');
    await this.runStageWithRetry('structure-pages', () =>
      this.executeStage(buildStructurePrompt(this.inputs, this.accumulated), 'sections')
    );
    this.onProgress?.(65, 'Sections and pages designed');

    // Stage 3: Features & SEO
    this.onProgress?.(70, 'Generating features and SEO strategy...');
    await this.runStageWithRetry('features-seo', () =>
      this.executeStage(buildFeaturesSeoPrompt(this.inputs, this.accumulated), 'features')
    );
    this.onProgress?.(90, 'Finalizing website plan');

    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> {
    console.log(`[WebsitePlanner-Pipeline] Executing stage "${primaryField}" 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(`[WebsitePlanner-Pipeline] Stage "${primaryField}" response received. Provider: ${result.provider}, Model: ${result.model}, Content length: ${result.content?.length || 0}`);
    console.log(`[WebsitePlanner-Pipeline] Stage "${primaryField}" 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(`[WebsitePlanner-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}`);
    }

    console.log(`[WebsitePlanner-Pipeline] Stage "${primaryField}" parsed keys: ${Object.keys(parsed).join(', ')}`);
    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 = buildWebsitePlannerEnhancementPrompt(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) {
        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(`[WebsitePlanner-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[]> = {
      'website-core': ['websiteType', 'websiteGoal', 'primaryCTA'],
      'structure-pages': ['sections', 'pages'],
      'features-seo': ['features', 'targetKeywords'],
    };

    const criticalFields = stageCriticalFields[stageName] || [];
    for (const field of criticalFields) {
      if (!this.accumulated[field] || this.accumulated[field] === '') {
        if (!low.includes(field)) {
          low.push(field);
        }
      }
    }

    // Sections that arrive without copy are the failure the user actually sees:
    // the plan looks populated, but the Content step is empty and the website
    // generator has nothing to build from. Treat that as low confidence so the
    // enhancement pass fills it in rather than shipping a hollow plan.
    if (stageName === 'structure-pages' && Array.isArray(this.accumulated.sections)) {
      const sections = this.accumulated.sections as any[];
      const withCopy = sections.filter(
        (s) => typeof s?.headline === 'string' && s.headline.trim().length > 0,
      ).length;
      if (sections.length > 0 && withCopy < sections.length / 2 && !low.includes('sections')) {
        console.warn(
          `[WebsitePlanner-Pipeline] Only ${withCopy}/${sections.length} sections came back with copy — requesting an enhancement pass`,
        );
        low.push('sections');
      }
    }

    return low;
  }

  private getStageOutput(stageName: string): Record<string, any> {
    const stageFieldMap: Record<string, string[]> = {
      'website-core': ['name', 'domain', 'websiteType', 'websiteGoal', 'primaryCTA', 'secondaryCTA', 'targetAudience', 'country', 'language', 'seoTargetRegion', 'status', 'uiStyle'],
      'structure-pages': ['sections', 'pages'],
      'features-seo': ['features', 'targetKeywords', 'seoClusters', 'faqs', 'designReferences', 'animationNotes', 'responsiveNotes', 'accessibilityNotes'],
    };

    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', 'websiteType', 'websiteGoal', 'primaryCTA', 'secondaryCTA', 'targetAudience',
      'sections', 'pages',
      'features', 'targetKeywords', 'seoClusters',
    ];

    for (const field of allFields) {
      if (this.accumulated[field]) {
        confidences[field] = overall;
      }
    }

    return confidences;
  }
}