/**
 * Stage 5: ACT
 *
 * Applies learnings from analysis:
 * 1. Update memory files (feedback-patterns, quality-standards, jake-preferences, improvement-log)
 * 2. Recalibrate confidence thresholds
 * 3. Adjust HITL frequency for auto-approvable task types
 * 4. Log what changed
 */

import type { AnalysisResults, ApplyResult, CandidateRule } from "../types.js";
import type { ActionResult, PipelineConfig } from "./types.js";
import {
  writeFeedbackPatterns,
  writeQualityStandards,
  writeJakePreferences,
  appendImprovementLog,
} from "../memory/writer.js";

/**
 * Apply analysis results by updating memory files and thresholds.
 */
export async function applyLearnings(
  analysis: AnalysisResults,
  config: PipelineConfig
): Promise<ActionResult> {
  try {
    const result: ApplyResult = {
      memoryFilesUpdated: [],
      rulesAdded: [],
      thresholdsChanged: [],
      autonomyLevelChanges: [],
    };

    const memDir = config.memoryDir;

    // 1. Update feedback patterns memory file
    if (analysis.themes.length > 0 || analysis.candidateRules.length > 0) {
      await writeFeedbackPatterns(memDir, {
        themes: analysis.themes,
        candidateRules: analysis.candidateRules,
        totalEvents: analysis.approvalPatterns.overall.totalDecisions,
      });
      result.memoryFilesUpdated.push("feedback-patterns.md");
    }

    // 2. Update quality standards memory file
    if (analysis.dimensionTrends.length > 0) {
      await writeQualityStandards(memDir, {
        dimensionTrends: analysis.dimensionTrends,
        calibration: analysis.calibration,
      });
      result.memoryFilesUpdated.push("quality-standards.md");
    }

    // 3. Update Jake's preferences memory file
    if (analysis.approvalPatterns.overall.totalDecisions > 0) {
      await writeJakePreferences(memDir, {
        approvalPatterns: analysis.approvalPatterns,
        dimensionTrends: analysis.dimensionTrends,
      });
      result.memoryFilesUpdated.push("jake-preferences.md");
    }

    // 4. Add high-confidence rules
    const highConfidenceRules = analysis.candidateRules.filter(
      (r) => r.confidence >= 0.8 && r.occurrences >= config.minDataPointsForRules
    );
    result.rulesAdded = highConfidenceRules;

    // 5. Track threshold changes from dimension trends
    for (const trend of analysis.dimensionTrends) {
      if (trend.minimumThreshold !== undefined) {
        result.thresholdsChanged.push({
          dimension: trend.dimension,
          oldThreshold: 0, // Would come from previous state
          newThreshold: trend.minimumThreshold,
        });
      }
    }

    // 6. Log improvements
    if (
      result.rulesAdded.length > 0 ||
      result.thresholdsChanged.length > 0 ||
      result.autonomyLevelChanges.length > 0
    ) {
      await appendImprovementLog(memDir, {
        date: new Date().toISOString().split("T")[0]!,
        rulesAdded: result.rulesAdded,
        thresholdsChanged: result.thresholdsChanged,
        autonomyLevelChanges: result.autonomyLevelChanges,
        anomalies: analysis.anomalies,
      });
      result.memoryFilesUpdated.push("improvement-log.md");
    }

    return { success: true, result };
  } catch (error) {
    return {
      success: false,
      error: `Action stage failed: ${error instanceof Error ? error.message : String(error)}`,
    };
  }
}
