// ============================================================
// ai-settings-client.jsx — wrapper FE per /api/settings/ai e /api/ai/ping
// ============================================================
//
// FASE 2b.AI: il FE non gestisce più le chiavi API in localStorage.
// Le chiavi vivono cifrate nel DB; il FE legge solo il DTO con flag
// `hasClaudeKey`, `hasGeminiKey` e gli hint mascherati.
//
// `aiSettings` in `lgs.ai` localStorage può rimanere come cache di
// `provider/model/mode/temperature` ma NON memorizza più le chiavi:
// `cleanLocalAiKeys()` viene chiamato all'avvio dell'app per rimuoverle.

(function () {
  async function fetchAiSettings() {
    const res = await fetch('/api/settings/ai', { cache: 'no-store' });
    if (!res.ok) throw new Error('GET /api/settings/ai HTTP ' + res.status);
    const json = await res.json();
    return json.data;
  }

  async function patchAiSettings(patch, userId) {
    const res = await fetch('/api/settings/ai', {
      method: 'PATCH',
      headers: {
        'Content-Type': 'application/json',
        'X-Actor-Persona-Id': userId || '',
      },
      body: JSON.stringify(patch),
    });
    const json = await res.json().catch(() => null);
    if (!res.ok) {
      const msg = json?.error === 'validation_error'
        ? json.issues?.map(i => `${i.path?.join('.')}: ${i.message}`).join(' · ')
        : (json?.error || `HTTP ${res.status}`);
      throw new Error(msg || 'PATCH failed');
    }
    return json.data;
  }

  async function pingAi(provider, prompt, userId) {
    const res = await fetch('/api/ai/ping', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Actor-Persona-Id': userId || '',
      },
      body: JSON.stringify(prompt ? { provider, prompt } : { provider }),
    });
    const json = await res.json().catch(() => null);
    if (!res.ok) {
      const detail = json?.detail || json?.error || `HTTP ${res.status}`;
      throw new Error(detail);
    }
    return json.data; // { provider, model, text, latencyMs }
  }

  /** Rimuove eventuali chiavi residue salvate in localStorage da versioni precedenti. */
  function cleanLocalAiKeys() {
    try {
      const raw = localStorage.getItem('lgs.ai');
      if (!raw) return;
      const obj = JSON.parse(raw);
      if (obj.claudeKey || obj.geminiKey) {
        delete obj.claudeKey;
        delete obj.geminiKey;
        localStorage.setItem('lgs.ai', JSON.stringify(obj));
        console.info('[Veridanto] chiavi AI rimosse da localStorage (ora in DB cifrate).');
      }
    } catch {
      // ignore
    }
  }

  Object.assign(window, { fetchAiSettings, patchAiSettings, pingAi, cleanLocalAiKeys });
})();
