/**
 * Stage 4: ANALYZE
 *
 * Runs pattern detection, calibration updates, and rule extraction
 * on accumulated feedback data. Can run after every event or in batches.
 *
 * Delegates to analysis/ package for the actual computations.
 */

import type { EnrichedFeedbackEvent, AnalysisResults } from "../types.js";
import type { AnalysisResult, PipelineConfig } from "./types.js";
import { loadFeedbackEvents } from "../storage/feedback-store.js";
import { detectPatterns } from "../analysis/patterns.js";
import { computeCalibration } from "../analysis/calibration.js";
import { buildPreferenceModel } from "../analysis/preferences.js";
import { computeDimensionTrends } from "../analysis/dimensions.js";
import { analyzeBehavioral } from "../analysis/behavioral.js";

/**
 * Run full analysis on recent feedback data.
 */
export async function analyzeFeedback(
  config: PipelineConfig
): Promise<AnalysisResult> {
  try {
    const events = await loadFeedbackEvents(config.dataDir, config.analysisDays);

    if (events.length === 0) {
      return {
        success: true,
        results: createEmptyResults(),
        eventsAnalyzed: 0,
      };
    }

    // Run all analysis in parallel
    const [patterns, calibration, preferences, dimensions, behavioral] =
      await Promise.all([
        detectPatterns(events, config.minDataPointsForRules),
        computeCalibration(events),
        buildPreferenceModel(events),
        computeDimensionTrends(events),
        analyzeBehavioral(events),
      ]);

    const results: AnalysisResults = {
      approvalPatterns: preferences,
      dimensionTrends: dimensions,
      themes: patterns.themes,
      calibration,
      anomalies: [
        ...patterns.anomalies,
        ...behavioral.anomalies,
      ],
      candidateRules: patterns.candidateRules,
    };

    return {
      success: true,
      results,
      eventsAnalyzed: events.length,
    };
  } catch (error) {
    return {
      success: false,
      error: `Analysis failed: ${error instanceof Error ? error.message : String(error)}`,
    };
  }
}

function createEmptyResults(): AnalysisResults {
  return {
    approvalPatterns: {
      overall: { approvalRate: 0, totalDecisions: 0, avgTimeToDecisionMs: 0 },
      byServerType: {},
      byStage: {},
    },
    dimensionTrends: [],
    themes: [],
    calibration: {
      lastUpdated: new Date().toISOString(),
      totalDataPoints: 0,
      buckets: [],
      expectedCalibrationError: 0,
    },
    anomalies: [],
    candidateRules: [],
  };
}
