import fs from 'node:fs';
import { MetaConfig } from '../../config/meta.config';

/**
 * يولّد Blueprints للسياسات ذات الارتباط القوي والثابت.
 * mutation: "expand" لو الارتباط إيجابي قوي / "contract" لو سلبي قوي
 */
export function generateBlueprints(
  patterns: Array<{
    policyId: string;
    avgCorrelation: number;
    volatility: number;
    support: number;
    direction: 'positive' | 'negative';
  }>
) {
  const selected = patterns.filter(
    (p) =>
      Math.abs(p.avgCorrelation) >= MetaConfig.rewriteThreshold &&
      p.volatility <= MetaConfig.volatilityMax
  );

  const blueprints = selected.map((bp) => ({
    policyId: bp.policyId,
    version: Date.now(),
    baseCorrelation: Number(bp.avgCorrelation.toFixed(4)),
    volatility: Number(bp.volatility.toFixed(4)),
    support: bp.support,
    mutation: bp.direction === 'positive' ? 'expand' : 'contract',
    rationale:
      bp.direction === 'positive'
        ? 'توسيع نطاق السياسة بسبب ارتباط إيجابي قوي ومستقر.'
        : 'تقليص/كبح السياسة بسبب ارتباط سلبي قوي ومستقر.',
  }));

  persistBlueprints(blueprints);
  return blueprints;
}

function persistBlueprints(items: any[]) {
  fs.mkdirSync('./storage', { recursive: true });
  const path = MetaConfig.blueprintPath;
  const existing = fs.existsSync(path) ? JSON.parse(fs.readFileSync(path, 'utf8')) : [];
  const merged = [...existing, ...items].slice(-MetaConfig.maxBlueprints);
  fs.writeFileSync(path, JSON.stringify(merged, null, 2));
}
