// brain-api.jsx — Fetch layer : connecte le front aux CF Pages Functions
// Polling toutes les 30s, fallback sur mock data si API indisponible

const BrainAPI = (() => {
  const POLL_INTERVAL = 30_000; // 30s — aligné sur le Cache-Control du middleware
  const timers = {};
  const listeners = {};

  function on(event, cb) {
    (listeners[event] = listeners[event] || []).push(cb);
  }
  function emit(event, data) {
    (listeners[event] || []).forEach(cb => cb(data));
  }

  async function apiFetch(path) {
    const r = await fetch(`/api/${path}`);
    if (!r.ok) throw new Error(`API ${path} → ${r.status}`);
    return r.json();
  }

  // --- Bookings (Mira) ---
  async function fetchBookings() {
    try {
      const data = await apiFetch('bookings');
      emit('bookings', data);
      return data;
    } catch (e) {
      console.warn('[Brain API] bookings:', e.message);
      return null;
    }
  }

  // --- Messages voyageurs (Yasmine) ---
  async function fetchMessages() {
    try {
      const data = await apiFetch('messages');
      emit('messages', data);
      return data;
    } catch (e) {
      console.warn('[Brain API] messages:', e.message);
      return null;
    }
  }

  // --- Workflows n8n (Brain) ---
  async function fetchWorkflows() {
    try {
      const data = await apiFetch('workflows');
      emit('workflows', data);
      return data;
    } catch (e) {
      console.warn('[Brain API] workflows:', e.message);
      return null;
    }
  }

  // --- Tâches Notion (tous agents) ---
  async function fetchTasks() {
    try {
      const data = await apiFetch('tasks');
      emit('tasks', data);
      return data;
    } catch (e) {
      console.warn('[Brain API] tasks:', e.message);
      return null;
    }
  }

  // --- Feed agrégé ---
  async function fetchFeed() {
    try {
      const data = await apiFetch('feed');
      emit('feed', data);
      return data;
    } catch (e) {
      console.warn('[Brain API] feed:', e.message);
      return null;
    }
  }

  // --- Jobs Agents (Notion) ---
  async function fetchJobs() {
    try {
      const data = await apiFetch('jobs');
      emit('jobs', data);
      return data;
    } catch (e) {
      console.warn('[Brain API] jobs:', e.message);
      return null;
    }
  }

  // --- Notifications (cron scripts → /tmp/brain-notifications.json) ---
  async function fetchNotifications() {
    try {
      const data = await apiFetch('notifications');
      emit('notifications', data);
      return data;
    } catch (e) {
      console.warn('[Brain API] notifications:', e.message);
      return null;
    }
  }

  // --- Bridge health ---
  async function fetchHealth() {
    try {
      const data = await apiFetch('health');
      emit('health', data);
      return data;
    } catch (e) {
      emit('health', { bridge: 'down', cockpit: 'ok' });
      return null;
    }
  }

  // --- Décisions en attente ---
  async function fetchDecisions() {
    try {
      const data = await apiFetch('decisions');
      emit('decisions', data);
      return data;
    } catch (e) {
      console.warn('[Brain API] decisions:', e.message);
      return null;
    }
  }

  // --- Polling loop ---
  function startPolling() {
    // Initial fetch — tout en parallèle
    fetchAll();
    // Puis poll toutes les 30s
    timers.main = setInterval(fetchAll, POLL_INTERVAL);
  }

  function stopPolling() {
    clearInterval(timers.main);
  }

  async function fetchAll() {
    await Promise.allSettled([
      fetchBookings(),
      fetchMessages(),
      fetchWorkflows(),
      fetchTasks(),
      fetchFeed(),
      fetchDecisions(),
      fetchJobs(),
      fetchHealth(),
      fetchNotifications(),
    ]);
    emit('refreshed', { at: new Date().toISOString() });
  }

  return {
    on,
    fetchBookings,
    fetchMessages,
    fetchWorkflows,
    fetchTasks,
    fetchFeed,
    fetchDecisions,
    fetchJobs,
    fetchHealth,
    fetchNotifications,
    fetchAll,
    startPolling,
    stopPolling,
  };
})();

window.BrainAPI = BrainAPI;
