/**
 * components/voice_engine.jsx
 *
 * Low-level helpers for VoiceChat: apiCall, matchDSL, executeDSL, formatToolResult.
 * Depends on globals from voice_schemas.jsx (ACTION_SCHEMA, TOOL_DISPATCH).
 */

let _proxymBase = '', _apiKey = '';

async function apiCall(method, path, body = null) {
  const opts = {
    method,
    headers: {
      'Authorization': `Bearer ${_apiKey}`,
      'Content-Type': 'application/json',
    },
  };
  if (body) opts.body = JSON.stringify(body);
  const r = await fetch(`${_proxymBase}${path}`, opts);
  if (!r.ok) {
    const err = await r.json().catch(() => ({ detail: r.statusText }));
    throw new Error(err.detail || `HTTP ${r.status}`);
  }
  return r.json().catch(() => ({}));
}

function matchDSL(text) {
  const t = text.trim();
  for (const rule of ACTION_SCHEMA) {
    for (const pattern of rule.patterns) {
      const m = t.match(pattern);
      if (m) {
        const captured = rule.captureGroup != null ? m[rule.captureGroup] : null;
        return { rule, captured };
      }
    }
  }
  return null;
}

async function executeDSL(rule, captured) {
  let { method, path } = rule.action;
  if (captured) path = path.replace('{0}', captured);
  const data = await apiCall(method, path);
  if (rule.then) rule.then(data);
  return typeof rule.success === 'function' ? rule.success(data) : 'Gotowe.';
}

function formatToolResult(name, data) {
  switch (name) {
    case 'vscode_start':
      if (data.url) window.open(data.url, '_blank');
      return `VS Code ${data.running ? 'uruchomiony' : 'jest już uruchomiony'}. ${data.url || ''}`;
    case 'vm_action': {
      const vms = data.vms || data || [];
      if (Array.isArray(vms)) {
        return `Masz ${vms.length} VM-ów, ${vms.filter(v => v.state === 'running').length} aktywnych.`;
      }
      return `Operacja na VM zakończona.`;
    }
    case 'get_costs':
      return `Dziś: $${(data.daily_usd || 0).toFixed(3)}. Miesiąc: $${(data.monthly_usd || 0).toFixed(2)}.`;
    case 'get_status':
      return `proxym ${data.status === 'ok' ? 'działa' : 'ma problem'}.`;
    case 'get_logs': {
      const logs = data.logs || [];
      return logs.length ? `${logs.length} błędów. Ostatni: ${logs[0].message?.slice(0, 60)}.` : 'Brak błędów.';
    }
    default:
      return JSON.stringify(data).slice(0, 100);
  }
}
