/**
 * Step 2.5: Competitor Deep Analysis - SEO Intelligence Phase 2 Sprint 4
 *
 * @module planning/seo/lib/steps/step-2.5-competitor-analysis
 * @description Execute deep competitor analysis and store results in Redis context
 */

import { PipelineContext } from '../../types';
import { RedisContextStore } from '../redis-context-store';
import { CompetitorDeepAnalyst } from '@claude-flow-novice/seo-analysis/lib/competitor-deep-analyst';
import {
  CompetitorAnalysisConfig,
  CompetitorAnalysisResult,
} from '@claude-flow-novice/seo-analysis/types/competitor-analysis';

/**
 * Step 2.5 configuration
 */
export interface Step2_5Config {
  /** Redis context store instance */
  redisContextStore: RedisContextStore;

  /** Enable verbose logging */
  verbose?: boolean;

  /** Maximum pages to crawl per competitor (default: 50) */
  maxPages?: number;

  /** Maximum crawl depth (default: 3) */
  maxDepth?: number;

  /** Rate limit delay between requests (ms, default: 1000) */
  rateLimitMs?: number;

  /** Request timeout (ms, default: 30000) */
  requestTimeoutMs?: number;
}

/**
 * Step 2.5 execution result
 */
export interface Step2_5Result {
  /** Number of competitors analyzed */
  competitorsAnalyzed: number;

  /** Total pages crawled across all competitors */
  totalPagesCrawled: number;

  /** Total hub pages identified */
  totalHubPages: number;

  /** Total architecture patterns extracted */
  totalArchitecturePatterns: number;

  /** Total content strategy patterns extracted */
  totalContentPatterns: number;

  /** Total content gaps identified */
  totalContentGaps: number;

  /** Analysis confidence score (0.0-1.0) */
  confidence: number;

  /** Execution time (ms) */
  executionTime: number;

  /** Warnings encountered during analysis */
  warnings: string[];
}

/**
 * Execute Step 2.5: Competitor Deep Analysis
 *
 * Performs comprehensive competitor analysis including:
 * - Site-wide crawling (50+ pages with depth control)
 * - Hub page identification
 * - Site architecture pattern extraction
 * - Content strategy analysis
 * - Internal linking pattern discovery
 * - Content gap identification
 *
 * Results are stored in Redis context for downstream pipeline steps.
 *
 * @param context - Pipeline execution context
 * @param config - Step 2.5 configuration
 * @returns Step 2.5 execution result
 */
export async function executeStep2_5(
  context: PipelineContext,
  config: Step2_5Config
): Promise<Step2_5Result> {
  const startTime = Date.now();
  const warnings: string[] = [];

  if (config.verbose) {
    console.log('[Step 2.5] Competitor Deep Analysis starting...');
    console.log(`[Step 2.5] Target keyword: ${context.task.targetKeyword}`);
    console.log(`[Step 2.5] Competitors: ${context.task.competitorDomains?.join(', ') || 'None'}`);
  }

  // Validate competitor domains
  if (!context.task.competitorDomains || context.task.competitorDomains.length === 0) {
    const warning = 'No competitor domains specified, skipping competitor analysis';
    warnings.push(warning);

    if (config.verbose) {
      console.warn(`[Step 2.5] ${warning}`);
    }

    return {
      competitorsAnalyzed: 0,
      totalPagesCrawled: 0,
      totalHubPages: 0,
      totalArchitecturePatterns: 0,
      totalContentPatterns: 0,
      totalContentGaps: 0,
      confidence: 1.0, // High confidence in intentional skip
      executionTime: Date.now() - startTime,
      warnings,
    };
  }

  // Validate API key configuration
  const firecrawlApiKey = process.env.FIRECRAWL_API_KEY;
  if (!firecrawlApiKey || firecrawlApiKey === '[REDACTED]') {
    throw new Error(
      'Firecrawl API key not configured. Set FIRECRAWL_API_KEY environment variable.'
    );
  }

  // Initialize aggregated results
  const aggregatedResults: CompetitorAnalysisResult[] = [];
  let totalPagesCrawled = 0;
  let totalHubPages = 0;
  let totalArchitecturePatterns = 0;
  let totalContentPatterns = 0;
  let totalContentGaps = 0;

  // Analyze each competitor
  for (const domain of context.task.competitorDomains) {
    try {
      if (config.verbose) {
        console.log(`[Step 2.5] Analyzing competitor: ${domain}`);
      }

      // Build competitor analysis config
      const analysisConfig: CompetitorAnalysisConfig = {
        domain,
        maxPages: config.maxPages || 50,
        maxDepth: config.maxDepth || 3,
        rateLimitMs: config.rateLimitMs || 1000,
        requestTimeoutMs: config.requestTimeoutMs || 30000,
        verbose: config.verbose || false,
        firecrawlApiKey,
      };

      // Create analyst and execute analysis
      const analyst = new CompetitorDeepAnalyst(analysisConfig);
      const result = await analyst.analyze();

      // Accumulate metrics
      totalPagesCrawled += result.pagesCrawled;
      totalHubPages += result.hubPages.length;
      totalArchitecturePatterns += result.architecturePatterns.length;
      totalContentPatterns += result.contentStrategyPatterns.length;
      totalContentGaps += result.contentGaps.length;

      // Store result
      aggregatedResults.push(result);

      if (config.verbose) {
        console.log(`[Step 2.5] Completed analysis for ${domain}:`);
        console.log(`  - Pages crawled: ${result.pagesCrawled}`);
        console.log(`  - Hub pages: ${result.hubPages.length}`);
        console.log(`  - Architecture patterns: ${result.architecturePatterns.length}`);
        console.log(`  - Content patterns: ${result.contentStrategyPatterns.length}`);
        console.log(`  - Content gaps: ${result.contentGaps.length}`);
        console.log(`  - Confidence: ${result.confidence.toFixed(2)}`);
      }

      // Collect warnings from analyst
      if (result.warnings && result.warnings.length > 0) {
        warnings.push(...result.warnings.map((w) => `${domain}: ${w}`));
      }
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      const warning = `Failed to analyze ${domain}: ${errorMessage}`;
      warnings.push(warning);

      if (config.verbose) {
        console.error(`[Step 2.5] ${warning}`);
      }

      // Continue with other competitors
      continue;
    }
  }

  // Calculate overall confidence
  const avgConfidence =
    aggregatedResults.length > 0
      ? aggregatedResults.reduce((sum, r) => sum + r.confidence, 0) / aggregatedResults.length
      : 0.5;

  // Store results in Redis context for downstream steps
  await config.redisContextStore.setContext(context.task.taskId, 'competitorAnalysisResults', {
    results: aggregatedResults,
    aggregatedMetrics: {
      totalCompetitors: aggregatedResults.length,
      totalPagesCrawled,
      totalHubPages,
      totalArchitecturePatterns,
      totalContentPatterns,
      totalContentGaps,
      avgConfidence,
    },
    analyzedAt: new Date().toISOString(),
  });

  if (config.verbose) {
    console.log('[Step 2.5] Competitor analysis results stored in Redis context');
    console.log(`[Step 2.5] Total execution time: ${Date.now() - startTime}ms`);
  }

  return {
    competitorsAnalyzed: aggregatedResults.length,
    totalPagesCrawled,
    totalHubPages,
    totalArchitecturePatterns,
    totalContentPatterns,
    totalContentGaps,
    confidence: avgConfidence,
    executionTime: Date.now() - startTime,
    warnings,
  };
}
