/**
 * @file neural-summary-generator.ts
 * Dynamic, deterministic text summaries for Jemy-dev OS.
 * Focus: logic-only (no I/O) so it's easy to unit-test.
 */

import type { EvolutionLog } from '@/lib/evolution/history.collector';

export type NeuralSummaryParts = {
  avgConfidence: number; // 0..1
  recentDrift: number; // -1..1  (difference of last vs value N-3)
  momentum: number; // average changeRate (%)
  dominantTrend: EvolutionLog['trend'];
  lastTimestamp: string; // ISO
};

export function calcNeuralStats(logs: EvolutionLog[]): NeuralSummaryParts {
  if (!logs || logs.length === 0) {
    return {
      avgConfidence: 0,
      recentDrift: 0,
      momentum: 0,
      dominantTrend: 'Reform',
      lastTimestamp: new Date(0).toISOString(),
    };
  }

  const avgConfidence = logs.reduce((s, l) => s + (l.confidence ?? 0), 0) / logs.length;

  const N = logs.length;
  const last = logs[N - 1];
  const compareIdx = Math.max(0, N - 3);
  const recentDrift = (last.confidence ?? 0) - (logs[compareIdx].confidence ?? 0);

  const momentum = logs.reduce((s, l) => s + (l.changeRate ?? 0), 0) / logs.length;

  return {
    avgConfidence,
    recentDrift,
    momentum,
    dominantTrend: last.trend,
    lastTimestamp: last.timestamp,
  };
}

export function toneForConfidence(avg: number): string {
  if (avg >= 0.75) return 'high stability with confident adaptation';
  if (avg >= 0.5) return 'moderate stability and ongoing adjustments';
  if (avg >= 0.35) return 'fluctuating state; caution advised';
  return 'low equilibrium — neural noise detected';
}

export function directionForTrend(trend: EvolutionLog['trend']): string {
  if (trend === 'Integrate') return 'cohesion and synthesis are increasing';
  if (trend === 'Reset') return 'disruption followed by structural reformation';
  return 'adaptive restructuring patterns dominate'; // Reform (default)
}

export function driftSentence(drift: number): string {
  if (drift > 0.02) return 'Confidence is rising steadily.';
  if (drift < -0.02) return 'Confidence decline detected; monitor closely.';
  return 'Confidence remains relatively flat.';
}

export function momentumSentence(momentum: number): string {
  if (momentum > 10) return 'Change momentum is strong to the upside.';
  if (momentum > 2) return 'Mild positive momentum observed.';
  if (momentum < -10) return 'Strong negative momentum present.';
  if (momentum < -2) return 'Mild negative momentum observed.';
  return 'Momentum is neutral.';
}

/**
 * Main generator — returns a deterministic human-readable summary.
 */
export function generateNeuralSummary(logs: EvolutionLog[]): string {
  const stats = calcNeuralStats(logs);
  const tone = toneForConfidence(stats.avgConfidence);
  const direction = directionForTrend(stats.dominantTrend);
  const driftStr = driftSentence(stats.recentDrift);
  const momentumStr = momentumSentence(stats.momentum);

  return [
    '🧠 Neural Predictive Report',
    '────────────────────────────',
    `Timestamp: ${new Date(stats.lastTimestamp).toLocaleString()}`,
    `Dominant Trend: ${stats.dominantTrend}`,
    `Average Confidence: ${(stats.avgConfidence * 100).toFixed(1)}%`,
    `Recent Drift: ${(stats.recentDrift * 100).toFixed(2)}%`,
    `Momentum: ${stats.momentum.toFixed(2)}%`,
    '────────────────────────────',
    `→ The system exhibits ${direction}.`,
    `→ ${tone}.`,
    `→ ${driftStr}`,
    `→ ${momentumStr}`,
  ].join('\n');
}
