/**
 * @file policy_history.ts
 * Phase 8.6 — Policy Heatmap Recorder
 * -----------------------------------
 * يحتفظ بتاريخ كل snapshots بيئية في ملف policy_history.json
 * ويحسب Environment Confidence Index (ECI)
 */

import fs from 'node:fs';
import path from 'node:path';
import { PolicySnapshot } from '../policies/PolicyManager';

const historyPath = path.resolve('./storage/policy_history.json');

function calcECI(snapshot: PolicySnapshot): number {
  // مؤشر الثقة البيئية (0 → سيئ جداً، 1 → ممتاز)
  const perfScore = { low: 0.3, medium: 0.7, high: 1 }[snapshot.performance];
  const netScore = { offline: 0.1, slow: 0.5, fast: 1 }[snapshot.network];
  const motionScore = snapshot.motion === 'full' ? 1 : 0.7;
  return Number(((perfScore + netScore + motionScore) / 3).toFixed(2));
}

export function appendPolicyHistory(snapshot: PolicySnapshot) {
  if (!fs.existsSync(path.dirname(historyPath)))
    fs.mkdirSync(path.dirname(historyPath), { recursive: true });

  const history = fs.existsSync(historyPath)
    ? JSON.parse(fs.readFileSync(historyPath, 'utf8'))
    : [];

  const entry = { ...snapshot, eci: calcECI(snapshot) };
  history.push(entry);
  fs.writeFileSync(historyPath, JSON.stringify(history, null, 2));
  console.log(`📊 [Heatmap] Policy snapshot added (${entry.eci * 100}% confidence).`);
}

export function getLastPolicyECI(): number {
  if (!fs.existsSync(historyPath)) return 0;
  const history = JSON.parse(fs.readFileSync(historyPath, 'utf8'));
  return history.at(-1)?.eci || 0;
}
