/**
 * يبني خريطة سببية تربط السياسات بالتغييرات والنتائج.
 */

import { EvolutionConfig } from '../../config/evolution.config';
import { ConsciousConfig } from '../../config/conscious.config';

export function buildCausalMap(
  registryBefore: any[],
  registryAfter: any[],
  metricsBefore: any,
  metricsAfter: any
) {
  const links = [];

  for (const policy of registryAfter) {
    const before = registryBefore.find((p) => p.policyId === policy.policyId);
    if (!before) continue;

    const deltaWeight = policy.weight - before.weight;
    const deltaScore = metricsAfter.evolutionScore - metricsBefore.evolutionScore;

    const correlation = correlateChange(deltaWeight, deltaScore);

    if (
      Math.abs(deltaScore) >= ConsciousConfig.insightThreshold &&
      Math.abs(correlation) >= ConsciousConfig.minCorrelation
    ) {
      links.push({
        policyId: policy.policyId,
        deltaWeight,
        deltaScore,
        correlation,
        cause: correlation > 0 ? 'positive' : 'negative',
      });
    }
  }

  return links;
}

/**
 * خوارزمية بسيطة لتقدير العلاقة بين التغيرات.
 */
function correlateChange(deltaWeight: any, deltaScore: any) {
  if (deltaWeight === 0) return 0;
  return deltaScore / deltaWeight; // تقريب بسيط للعلاقة
}
