/**
 * Phase 8.5 — Responsive Collective Dashboard 🧠
 * ----------------------------------------------
 * Unified display of Integration_Report.json + Responsive Policy context
 * Supports environment awareness (device/performance/motion/network)
 * before transition to Phase 9 (Predictive Evolution).
 *
 * 🧩 Layers included:
 *  - Evolution Report Awareness
 *  - Responsive Policy Awareness
 *  - Telemetry Logging
 *  - Dynamic UI density and motion
 *
 * CLI + React Dual Mode: Works both as interactive React component and CLI renderer.
 */

import fs from 'node:fs';
import path from 'node:path';
import chalk from 'chalk';
import boxen from 'boxen';
import React, { useEffect } from 'react';
import { usePolicy } from '../../context/PolicyContext';
import { appendPolicyTelemetry } from '../integration/policy_telemetry';

// ============ Types ============
interface IntegrationReport {
  timestamp: string;
  nodes: Array<{ nodeId: string; trust: number }>;
  metrics: {
    collectiveStability: number;
    collaborationIndex: number;
    metaResonance: number;
    nextEvolutionDirective: 'Expand' | 'Contract' | 'Freeze' | 'Merge';
  };
  notes: {
    interpretation: string;
    guidance: string;
  };
}

function colorValue(v: number): string {
  if (v >= 0.7) return chalk.green(`${(v * 100).toFixed(1)}%`);
  if (v >= 0.4) return chalk.yellow(`${(v * 100).toFixed(1)}%`);
  return chalk.red(`${(v * 100).toFixed(1)}%`);
}

function emojiForDirective(dir: string): string {
  switch (dir) {
    case 'Expand': return '🚀';
    case 'Merge': return '🫱🏼‍🫲🏽';
    case 'Freeze': return '🧊';
    case 'Contract': return '🌀';
    default: return '❓';
  }
}

// ===============================================================
// 🧠 React Component Mode — aware of device and motion context
// ===============================================================
export const CollectiveDashboard: React.FC = () => {
  const policy = usePolicy();

  // 🔄 Log telemetry when environment changes
  useEffect(() => {
    appendPolicyTelemetry(policy);
  }, [policy]);

  const density = policy.device === 'mobile' ? 'compact' : 'spacious';
  const motion = policy.motion === 'reduced' ? 'minimal' : 'animated';
  const perf = policy.performance === 'low' ? chalk.red('⚠️ Low Performance') : chalk.green('✅ Stable');

  const infoBox = boxen(
    `
📱  Device: ${policy.device}
⚙️  Performance: ${policy.performance}
🌐  Network: ${policy.network}
🎞️  Motion: ${policy.motion}
🧩  Density: ${density}
${perf}
`, { padding: 1, borderColor: 'magenta', borderStyle: 'round', title: 'Responsive Policy' }
  );

  console.log(chalk.cyan('\n🧠 Collective Dashboard (Responsive Mode)\n'));
  console.log(infoBox);

  // Render static dashboard CLI view
  showCollectiveDashboard();
  return null;
};

// ===============================================================
// 🧩 CLI Renderer — reads Integration_Report.json and displays
// ===============================================================
export function showCollectiveDashboard(reportPath = './storage/Integration_Report.json') {
  if (!fs.existsSync(reportPath)) {
    console.error(chalk.red(`❌ لم يتم العثور على ${reportPath}`));
    process.exit(1);
  }

  const json: IntegrationReport = JSON.parse(fs.readFileSync(reportPath, 'utf8'));
  const { metrics, timestamp, notes } = json;

  const rows = [
    ['🩺 Stability', colorValue(metrics.collectiveStability)],
    ['🤝 Collaboration', colorValue(metrics.collaborationIndex)],
    ['💭 Meta Resonance', colorValue(metrics.metaResonance)],
    ['⚡ Directive', `${emojiForDirective(metrics.nextEvolutionDirective)}  ${chalk.bold(metrics.nextEvolutionDirective)}`],
  ];

  const table =
    '╔══════════════════════════════════════════════╗\n' +
    rows.map(([k, v]) => `║ ${chalk.cyanBright(k.padEnd(20))} → ${v.padEnd(15)} ║`).join('\n') +
    '\n╚══════════════════════════════════════════════╝';

  const box = boxen(
    `
🧠  Collective Dashboard
────────────────────────────
📅  ${chalk.gray(timestamp)}

${table}

💬  ${chalk.blueBright(notes.interpretation)}
🧭  ${chalk.yellow(notes.guidance)}
`,
    { padding: 1, margin: 1, borderStyle: 'round', borderColor: 'cyan' }
  );

  console.log(box);
}

// ===============================================================
// CLI Execution Mode
// ===============================================================
if (process.argv[1]?.includes('collective_dashboard')) {
  showCollectiveDashboard();
}
