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

/**
 * يقرأ conscious_insights.json ويستخرج نمطًا ميتا لكل سياسة:
 * - avgCorrelation: متوسط الارتباط
 * - volatility: تذبذب الارتباط
 * - support: عدد الملاحظات المحسوبة
 * - direction: positive/negative
 */
export function detectMetaPatterns() {
  const path = ConsciousConfig.storagePath;
  if (!fs.existsSync(path)) return [];

  const all = JSON.parse(fs.readFileSync(path, 'utf8')) as Array<{
    policyId: string;
    correlation: string | number; // محفوظ كنص أحيانًا
    timestamp: string;
  }>;

  // تجميع حسب السياسة + قطع لأحدث window
  const grouped: Record<string, number[]> = {};
  for (const ins of all) {
    const id = ins.policyId;
    const c = typeof ins.correlation === 'string' ? Number(ins.correlation) : ins.correlation;
    if (!Number.isFinite(c)) continue;
    grouped[id] ??= [];
    grouped[id].push(c);
  }

  const patterns = Object.entries(grouped).map(([policyId, corrs]) => {
    const recent = corrs.slice(-MetaConfig.patternWindow);
    const support = recent.length;

    const avg = mean(recent);
    const vol = Math.sqrt(mean(recent.map((x) => (x - avg) ** 2))); // الانحراف المعياري
    const direction = avg >= 0 ? 'positive' : ('negative' as const);

    return { policyId, avgCorrelation: avg, volatility: vol, support, direction };
  });

  // فلترة أساسية
  return patterns.filter((p) => p.support >= MetaConfig.minSupport);
}

const mean = (arr: number[]) => (arr.length ? arr.reduce((a, b) => a + b, 0) / arr.length : 0);
