/**
 * Step 3.5: SERP Pattern Analysis - SEO Intelligence Phase 2 Sprint 4
 *
 * @module planning/seo/lib/steps/step-3.5-serp-pattern-analysis
 * @description Execute SERP pattern analysis and store results in Redis context
 */

import { PipelineContext } from '../../types';
import { RedisContextStore } from '../redis-context-store';
import { SERPPatternAnalyst } from '@claude-flow-novice/seo-analysis/lib/serp-pattern-analyst';
import {
  SERPAnalysisConfig,
  SERPAnalysisResult,
} from '@claude-flow-novice/seo-analysis/types/serp-analysis';

/**
 * Step 3.5 configuration
 */
export interface Step3_5Config {
  /** Redis context store instance */
  redisContextStore: RedisContextStore;

  /** Enable verbose logging */
  verbose?: boolean;

  /** Maximum SERP results to analyze (default: 10) */
  maxResults?: number;

  /** Enable content scraping for deeper semantic analysis */
  enableContentScraping?: boolean;

  /** Rate limit delay between requests (ms, default: 1000) */
  rateLimitMs?: number;

  /** Request timeout (ms, default: 30000) */
  requestTimeoutMs?: number;

  /** Google Custom Search API key (optional, uses env var if not provided) */
  googleApiKey?: string;

  /** Google Custom Search Engine ID (optional, uses env var if not provided) */
  googleSearchEngineId?: string;

  /** DataForSEO API key as alternative to Google Custom Search */
  dataForSeoApiKey?: string;
}

/**
 * Step 3.5 execution result
 */
export interface Step3_5Result {
  /** Target keyword analyzed */
  keyword: string;

  /** Number of SERP results analyzed */
  resultsAnalyzed: number;

  /** Number of SERP features detected */
  featuresDetected: number;

  /** Number of ranking patterns identified */
  rankingPatterns: number;

  /** Number of semantic clusters found */
  semanticClusters: number;

  /** Number of recommendations generated */
  recommendations: number;

  /** Analysis confidence score (0.0-1.0) */
  confidence: number;

  /** Execution time (ms) */
  executionTime: number;

  /** Warnings encountered during analysis */
  warnings: string[];
}

/**
 * Execute Step 3.5: SERP Pattern Analysis
 *
 * Performs comprehensive SERP pattern analysis including:
 * - SERP feature detection (featured snippets, PAA, knowledge panels, etc.)
 * - Ranking pattern analysis across top results
 * - Semantic clustering and topic extraction
 * - Content length and structure analysis
 * - Domain authority pattern detection
 * - Actionable recommendation generation
 *
 * Results are stored in Redis context for downstream pipeline steps.
 *
 * @param context - Pipeline execution context
 * @param config - Step 3.5 configuration
 * @returns Step 3.5 execution result
 */
export async function executeStep3_5(
  context: PipelineContext,
  config: Step3_5Config
): Promise<Step3_5Result> {
  const startTime = Date.now();
  const warnings: string[] = [];

  if (config.verbose) {
    console.log('[Step 3.5] SERP Pattern Analysis starting...');
    console.log(`[Step 3.5] Target keyword: ${context.task.targetKeyword}`);
  }

  // Validate API key configuration
  const googleApiKey = config.googleApiKey || process.env.GOOGLE_API_KEY;
  const googleSearchEngineId = config.googleSearchEngineId || process.env.GOOGLE_SEARCH_ENGINE_ID;
  const dataForSeoApiKey = config.dataForSeoApiKey || process.env.DATA_FOR_SEO_API_KEY;

  const hasGoogleConfig = googleApiKey && googleSearchEngineId;
  const hasDataForSeoConfig = dataForSeoApiKey;

  if (!hasGoogleConfig && !hasDataForSeoConfig) {
    throw new Error(
      'No SERP API configured. Set GOOGLE_API_KEY + GOOGLE_SEARCH_ENGINE_ID or DATA_FOR_SEO_API_KEY environment variables.'
    );
  }

  // Validate API keys are not placeholders
  if (googleApiKey === '[REDACTED]' || googleSearchEngineId === '[REDACTED]') {
    throw new Error('Google API credentials contain placeholder values. Configure real API keys.');
  }

  if (dataForSeoApiKey === '[REDACTED]') {
    throw new Error('DataForSEO API key contains placeholder value. Configure real API key.');
  }

  try {
    // Build SERP analysis config
    const analysisConfig: SERPAnalysisConfig = {
      keyword: context.task.targetKeyword,
      maxResults: config.maxResults || 10,
      enableContentScraping: config.enableContentScraping || false,
      rateLimitMs: config.rateLimitMs || 1000,
      requestTimeoutMs: config.requestTimeoutMs || 30000,
      verbose: config.verbose || false,
      googleApiKey,
      googleSearchEngineId,
      dataForSeoApiKey,
    };

    if (config.verbose) {
      console.log('[Step 3.5] Analysis configuration:');
      console.log(`  - Max results: ${analysisConfig.maxResults}`);
      console.log(`  - Content scraping: ${analysisConfig.enableContentScraping ? 'enabled' : 'disabled'}`);
      console.log(`  - API provider: ${hasGoogleConfig ? 'Google Custom Search' : 'DataForSEO'}`);
    }

    // Create analyst and execute analysis
    const analyst = new SERPPatternAnalyst(analysisConfig);
    const result: SERPAnalysisResult = await analyst.analyze();

    if (config.verbose) {
      console.log('[Step 3.5] SERP analysis completed:');
      console.log(`  - Results analyzed: ${result.resultsAnalyzed}`);
      console.log(`  - Features detected: ${result.features.length}`);
      console.log(`  - Ranking patterns: ${result.rankingPatterns.length}`);
      console.log(`  - Semantic clusters: ${result.semanticClusters.length}`);
      console.log(`  - Recommendations: ${result.recommendations.length}`);
      console.log(`  - Confidence: ${result.confidence.toFixed(2)}`);
    }

    // Collect warnings from analyst
    if (result.warnings && result.warnings.length > 0) {
      warnings.push(...result.warnings);
    }

    // Store results in Redis context for downstream steps
    await config.redisContextStore.setContext(context.task.taskId, 'serpAnalysisResult', {
      keyword: context.task.targetKeyword,
      result,
      analyzedAt: new Date().toISOString(),
    });

    if (config.verbose) {
      console.log('[Step 3.5] SERP analysis results stored in Redis context');
      console.log(`[Step 3.5] Total execution time: ${Date.now() - startTime}ms`);
    }

    return {
      keyword: context.task.targetKeyword,
      resultsAnalyzed: result.resultsAnalyzed,
      featuresDetected: result.features.length,
      rankingPatterns: result.rankingPatterns.length,
      semanticClusters: result.semanticClusters.length,
      recommendations: result.recommendations.length,
      confidence: result.confidence,
      executionTime: Date.now() - startTime,
      warnings,
    };
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);

    if (config.verbose) {
      console.error(`[Step 3.5] Analysis failed: ${errorMessage}`);
    }

    throw new Error(`SERP pattern analysis failed for keyword "${context.task.targetKeyword}": ${errorMessage}`);
  }
}
