// lib/telemetry/policy.telemetry.ts
import type { Policy } from '../core/policies/types';
import { recordEvolutionEvent, upsertEvolutionReport } from './evolution.telemetry';

export function logPolicyApplied(policy: Policy) {
  const payload = {
    ts: new Date().toISOString(),
    device: policy.device,
    ui: policy.ui,
    behavior: policy.behavior,
    data: policy.data,
    meta: policy.meta ?? { confidence: 0 },
  };

  // سجل محليّ خاص بالسياسة
  try {
    const key = 'OS_POLICY_LOGS';
    const prev = JSON.parse(localStorage.getItem(key) || '[]');
    prev.push(payload);
    localStorage.setItem(key, JSON.stringify(prev.slice(-50)));
  } catch {}

  // 🔗 توحيد مع Evolution Telemetry
  try {
    recordEvolutionEvent('policy_applied', {
      device: policy.device,
      perfMode: policy.behavior.perfMode,
      animations: policy.ui.animations,
      density: policy.ui.density,
      confidence: policy.meta?.confidence ?? 0,
    });

    // تحديث تقرير التطوّر بآخر سياق معروف
    upsertEvolutionReport({
      lastContext: {
        device: policy.device,
        perfMode: policy.behavior.perfMode,
        animations: policy.ui.animations,
        density: policy.ui.density,
        confidence: policy.meta?.confidence ?? 0,
      },
      lastUpdated: payload.ts,
    });
  } catch {}
}
