/**
 * يولّد "أفكار" بشرية من الخريطة السببية.
 */

import fs from 'node:fs';
import { ConsciousConfig } from '../../config/conscious.config';

export function generateInsights(causalMap: any[]) {
  const insights = causalMap.map((link: any) => {
    const direction = link.cause === 'positive' ? 'تحسّن' : 'تدهور';
    return {
      policyId: link.policyId,
      summary: `السياسة ${link.policyId} أدت إلى ${direction} بمقدار ${Math.abs(
        link.deltaScore
      ).toFixed(3)}.`,
      weightChange: link.deltaWeight.toFixed(3),
      correlation: link.correlation.toFixed(3),
      timestamp: new Date().toISOString(),
    };
  });

  persistInsights(insights);
  return insights;
}

function persistInsights(insights: any) {
  fs.mkdirSync('./storage', { recursive: true });
  const path = ConsciousConfig.storagePath;
  const existing = fs.existsSync(path) ? JSON.parse(fs.readFileSync(path, 'utf8')) : [];
  const merged = [...existing, ...insights].slice(-ConsciousConfig.maxInsights);
  fs.writeFileSync(path, JSON.stringify(merged, null, 2));
}
