/**
 * Operator Registry Client
 * Fetches and caches the live catalogue of 1,500+ operators from API Gateway.
 * Supports search, category browsing, and single-operator lookup.
 *
 * @version 1.287.4
 * @license CC BY 4.0 — Zeq. H / Zeq 1.287 Hz Limited
 */
const OperatorClient = (() => {
  'use strict';

  const CACHE_KEY = 'zeq_operator_cache';
  const CACHE_TTL = 86400000; // 24 hours

  // ── Fetch all operators (cached) ──────────────────────────────────────
  async function getAll() {
    return new Promise((resolve, reject) => {
      chrome.runtime.sendMessage({ type: 'fetchOperatorRegistry' }, (response) => {
        if (chrome.runtime.lastError) { reject(chrome.runtime.lastError); return; }
        if (response?.success) resolve(response.data);
        else reject(new Error(response?.error || 'Failed to fetch operators'));
      });
    });
  }

  // ── Search operators by keyword ───────────────────────────────────────
  async function search(query) {
    return new Promise((resolve, reject) => {
      chrome.runtime.sendMessage({ type: 'searchOperators', query }, (response) => {
        if (chrome.runtime.lastError) { reject(chrome.runtime.lastError); return; }
        if (response?.success) resolve(response.data);
        else reject(new Error(response?.error || 'Search failed'));
      });
    });
  }

  // ── Get categories from cached data ───────────────────────────────────
  async function getCategories() {
    const all = await getAll();
    if (!all?.operators) return [];

    const cats = {};
    for (const op of all.operators) {
      const domain = op.domain || op.category || 'Unknown';
      if (!cats[domain]) cats[domain] = { name: domain, count: 0, operators: [] };
      cats[domain].count++;
      cats[domain].operators.push(op);
    }
    return Object.values(cats).sort((a, b) => b.count - a.count);
  }

  // ── Get single operator by ID ─────────────────────────────────────────
  async function getById(operatorId) {
    const all = await getAll();
    if (!all?.operators) return null;
    return all.operators.find(op => op.id === operatorId || op.code === operatorId) || null;
  }

  // ── Clear cache ───────────────────────────────────────────────────────
  function clearCache() {
    chrome.storage.local.remove(CACHE_KEY);
  }

  return { getAll, search, getCategories, getById, clearCache };
})();
