/**
 * Phase 6.3 — Adaptive Evolution Engine
 * يدمج A/B Simulation مع تحديث السجلات وتوليد تطور حقيقي.
 */

import fs from 'node:fs';
import { LongTermMemory } from '../memory/long_term_memory';
import { loadRegistry, saveRegistry } from '../policy/registry';
import { runABSimulation } from './ab_simulator';
import { EvolutionConfig } from '../../config/evolution.config';

/**
 * تشغيل دورة التطور التلقائي.
 */
export function runAdaptiveEvolution() {
  const memory = LongTermMemory.getState();
  const metrics = memory.metrics || { evolutionScore: 0 };
  const registry = loadRegistry();
  const evolutionLog = [];

  for (const policy of registry) {
    const sims = runABSimulation(policy, metrics);
    const accepted = sims.filter((s) => s.accepted);

    if (accepted.length > 0) {
      // نختار الأفضل
      const best = accepted.sort((a, b) => b.avgScore - a.avgScore)[0];
      policy.weight = best.newWeight;
      policy.trend = '↑';
      policy.lastUpdate = new Date().toISOString();
    }

    evolutionLog.push({
      policyId: policy.policyId,
      tested: sims.length,
      accepted: accepted.length,
      newWeight: policy.weight,
    });
  }

  saveRegistry(registry);
  persistLog(evolutionLog);
  return evolutionLog;
}

/**
 * حفظ سجل التطور.
 */
function persistLog(log) {
  fs.mkdirSync('./storage', { recursive: true });
  fs.writeFileSync(EvolutionConfig.evolutionLog, JSON.stringify(log, null, 2));
}
