/**
 * components/voice_schemas.jsx
 *
 * Action schema (regex → REST), tool schema (LLM tool_calling),
 * and tool dispatch map for VoiceChat.
 */

// ACTION SCHEMA
const ACTION_SCHEMA = [
  {
    patterns: [/uruchom\s+vscode/i, /start\s+vscode/i, /włącz\s+vscode/i, /otwórz\s+vscode/i, /open\s+vscode/i],
    action: { method: 'POST', path: '/api/v1/vscode/start' },
    confirm: false,
    label: 'Uruchamiam VS Code Web…',
    success: (d) => `VS Code uruchomiony. ${d.url ? 'Otwieramy: ' + d.url : 'Dostępny na porcie 8080.'}`,
    then: (d) => { if (d.url) window.open(d.url, '_blank'); },
  },
  {
    patterns: [/zatrzymaj\s+vscode/i, /stop\s+vscode/i, /wyłącz\s+vscode/i],
    action: { method: 'POST', path: '/api/v1/vscode/stop' },
    label: 'Zatrzymuję VS Code Web…',
    success: () => 'VS Code zatrzymany.',
  },
  {
    patterns: [/status\s+vscode/i, /czy\s+vscode\s+działa/i],
    action: { method: 'GET', path: '/api/v1/vscode/status' },
    label: 'Sprawdzam VS Code…',
    success: (d) => `VS Code: ${d.running ? `działa na porcie ${d.port}` : 'zatrzymany'}.`,
  },
  {
    patterns: [/pokaż\s+(vm|maszyn)/i, /lista\s+(vm|maszyn)/i, /jakie\s+maszyny/i, /show\s+vms?/i, /list\s+vms?/i],
    action: { method: 'GET', path: '/api/v1/vms' },
    label: 'Pobieram listę VM-ów…',
    success: (d) => {
      const vms = d.vms || d || [];
      if (!vms.length) return 'Brak VM-ów. Utwórz przez: proxym vm create.';
      const running = vms.filter(v => v.state === 'running');
      return `Masz ${vms.length} VM-ów, ${running.length} uruchomionych: ${running.map(v => v.vm_id || v.id).join(', ') || 'żaden'}.`;
    },
  },
  {
    patterns: [/uruchom\s+vm\s+([a-z0-9_-]+)/i, /start\s+vm\s+([a-z0-9_-]+)/i, /włącz\s+([a-z0-9_-]+)/i],
    captureGroup: 1,
    action: { method: 'POST', path: '/api/v1/vms/{0}/start' },
    label: (id) => `Uruchamiam VM ${id}…`,
    success: (d) => `VM ${d.vm_id || ''} uruchomiony.`,
  },
  {
    patterns: [/zatrzymaj\s+vm\s+([a-z0-9_-]+)/i, /stop\s+vm\s+([a-z0-9_-]+)/i, /wyłącz\s+([a-z0-9_-]+)/i],
    captureGroup: 1,
    action: { method: 'POST', path: '/api/v1/vms/{0}/stop' },
    label: (id) => `Zatrzymuję VM ${id}…`,
    success: (d) => `VM ${d.vm_id || ''} zatrzymany.`,
  },
  {
    patterns: [/snapshot\s+([a-z0-9_-]+)/i, /zapisz\s+stan\s+([a-z0-9_-]+)/i],
    captureGroup: 1,
    action: { method: 'POST', path: '/api/v1/vms/{0}/snapshot' },
    label: (id) => `Tworzę snapshot VM ${id}…`,
    success: () => 'Snapshot utworzony.',
  },
  {
    patterns: [/ile\s+wydałem/i, /koszty/i, /budżet/i, /costs?/i, /how\s+much/i],
    action: { method: 'GET', path: '/api/v1/dashboard/costs/summary' },
    label: 'Sprawdzam koszty…',
    success: (d) => {
      const daily = (d.daily_usd || 0).toFixed(3);
      const monthly = (d.monthly_usd || 0).toFixed(2);
      return `Dziś: $${daily}. Miesiąc: $${monthly}.`;
    },
  },
  {
    patterns: [/^status$/i, /jak\s+idzie/i, /co\s+działa/i, /pokaż\s+stan/i, /system\s+status/i],
    action: { method: 'GET', path: '/health' },
    label: 'Sprawdzam status…',
    success: (d) => `proxym ${d.status === 'ok' ? 'działa poprawnie' : 'ma problemy'}. Wersja: ${d.version || '?'}.`,
  },
  {
    patterns: [/logi?/i, /błędy?/i, /co\s+się\s+stało/i, /logs?/i, /errors?/i],
    action: { method: 'GET', path: '/api/v1/logs?lines=5&level=error' },
    label: 'Pobieramy logi…',
    success: (d) => {
      const logs = d.logs || [];
      if (!logs.length) return 'Brak błędów.';
      return `${logs.length} błędów. Ostatni: ${logs[0].message?.slice(0, 80) || '?'}`;
    },
  },
  {
    patterns: [/jakie\s+modele/i, /dostępne\s+modele/i, /list\s+models/i, /show\s+models/i],
    action: { method: 'GET', path: '/v1/models' },
    label: 'Pobieramy modele…',
    success: (d) => {
      const ids = (d.data || []).map(m => m.id).join(', ');
      return `Dostępne modele: ${ids}.`;
    },
  },
  {
    patterns: [/test\s+routing/i, /sprawdź\s+routing/i, /czy\s+działa\s+ollama/i, /test\s+ollama/i],
    action: { method: 'GET', path: '/api/v1/routing/test' },
    label: 'Testuję routing…',
    success: (d) => {
      const routes = d.routing || {};
      const ok = Object.entries(routes).filter(([, v]) => v.status === 'ok').map(([k]) => k);
      const fail = Object.entries(routes).filter(([, v]) => v.status !== 'ok').map(([k]) => k);
      return `Działa: ${ok.join(', ') || 'żaden'}. Niedostępne: ${fail.join(', ') || 'żaden'}.`;
    },
  },
  {
    patterns: [/pokaż\s+konta/i, /lista\s+kont/i, /jakie\s+konta/i, /list\s+accounts/i],
    action: { method: 'GET', path: '/api/v1/accounts' },
    label: 'Pobieramy konta…',
    success: (d) => {
      const accounts = d.accounts || d || [];
      return `Masz ${accounts.length} kont API: ${accounts.map(a => a.label || a.id).join(', ')}.`;
    },
  },
];

// TOOL SCHEMA (LLM tool_calling)
const TOOL_SCHEMA = [
  {
    type: 'function',
    function: {
      name: 'vscode_start',
      description: 'Uruchom usługę VS Code Web',
      parameters: { type: 'object', properties: {}, required: [] },
    },
  },
  {
    type: 'function',
    function: {
      name: 'vm_action',
      description: 'Zarządzaj maszyną wirtualną (start/stop/pause/snapshot)',
      parameters: {
        type: 'object',
        properties: {
          vm_id: { type: 'string', description: 'ID maszyny wirtualnej' },
          action: { type: 'string', enum: ['start', 'stop', 'pause', 'snapshot', 'list'] },
        },
        required: ['action'],
      },
    },
  },
  {
    type: 'function',
    function: {
      name: 'get_costs',
      description: 'Pobierz podsumowanie kosztów API',
      parameters: { type: 'object', properties: {}, required: [] },
    },
  },
  {
    type: 'function',
    function: {
      name: 'get_status',
      description: 'Sprawdź status systemu proxym',
      parameters: { type: 'object', properties: {}, required: [] },
    },
  },
  {
    type: 'function',
    function: {
      name: 'get_logs',
      description: 'Pobierz ostatnie logi błędów',
      parameters: {
        type: 'object',
        properties: {
          level: { type: 'string', enum: ['all', 'error', 'warning', 'info'], default: 'error' },
          lines: { type: 'integer', default: 10 },
        },
        required: [],
      },
    },
  },
];

const TOOL_DISPATCH = {
  vscode_start: () => apiCall('POST', '/api/v1/vscode/start'),
  vm_action: ({ action, vm_id }) => {
    if (action === 'list') return apiCall('GET', '/api/v1/vms');
    if (!vm_id) return apiCall('GET', '/api/v1/vms');
    return apiCall('POST', `/api/v1/vms/${vm_id}/${action}`);
  },
  get_costs: () => apiCall('GET', '/api/v1/dashboard/costs/summary'),
  get_status: () => apiCall('GET', '/health'),
  get_logs: ({ level = 'error', lines = 10 } = {}) => apiCall('GET', `/api/v1/logs?lines=${lines}&level=${level}`),
};
