{% extends "base.html" %}

{% block title %}API Console — Langfuse Lens{% endblock %}
{% block page_title %}<span data-i18n="apiConsole.title">API Console</span>{% endblock %}

{% block content %}
<div class="tabs" id="console-tabs">
  <button class="tab active" data-tab="tab-operations" data-i18n="apiConsole.operations">Operations</button>
  <button class="tab" data-tab="tab-execute" data-i18n="apiConsole.execute">Execute</button>
</div>

<!-- Operations -->
<div class="tab-panel active" id="tab-operations">
  <div class="card">
    <div class="card-header">
      <div class="card-title" data-i18n="apiConsole.operations">Operations</div>
      <input type="text" class="form-input" id="ops-filter" style="max-width:300px;margin:0" data-i18n-placeholder="apiConsole.filterPlaceholder" placeholder="Search operations..." />
    </div>
    <p id="ops-summary" class="text-sm text-muted mb-8"></p>
    <div id="ops-table">
      <div class="loading-center"><div class="spinner"></div></div>
    </div>
  </div>
</div>

<!-- Execute -->
<div class="tab-panel" id="tab-execute">
  <div class="card">
    <p id="exec-placeholder" class="text-muted" data-i18n="apiConsole.selectOperation">Select an operation to execute</p>
    <div id="exec-form" style="display:none">
      <div class="grid-2 gap-20 mb-16">
        <div class="detail-row">
          <div class="detail-label">Operation ID</div>
          <div class="detail-value td-mono" id="exec-op-id"></div>
        </div>
        <div class="detail-row">
          <div class="detail-label">Method / Path</div>
          <div class="detail-value" id="exec-method-path"></div>
        </div>
      </div>
      <div class="detail-row mb-16" id="exec-summary-row">
        <div class="detail-label" data-i18n="apiConsole.summary">Summary</div>
        <div class="detail-value" id="exec-summary"></div>
      </div>

      <div id="exec-path-params" class="mb-16" style="display:none">
        <label class="form-label" data-i18n="apiConsole.pathParams">Path Parameters</label>
        <div id="exec-path-fields"></div>
      </div>

      <div id="exec-query-params" class="mb-16" style="display:none">
        <label class="form-label" data-i18n="apiConsole.queryParams">Query Parameters</label>
        <div id="exec-query-fields"></div>
      </div>

      <div class="form-group" id="exec-body-group" style="display:none">
        <label class="form-label" data-i18n="apiConsole.requestBody">Request Body (JSON)</label>
        <textarea class="form-input" id="exec-body" rows="6" style="font-family:var(--font-mono);font-size:13px" placeholder="{}"></textarea>
      </div>

      <button class="btn btn-primary" id="exec-btn" data-i18n="apiConsole.executeBtn">Execute</button>

      <div id="exec-response-wrap" class="mt-16" style="display:none">
        <label class="form-label" data-i18n="apiConsole.response">Response</label>
        <pre id="exec-response" class="pre-wrap" style="max-height:400px;overflow:auto"></pre>
      </div>
    </div>
  </div>
</div>
{% endblock %}

{% block scripts %}
<script type="module">
import { api } from '/static/js/api.js';
import { toast, escapeHtml, initTabs, showLoading, showEmpty, t } from '/static/js/common.js';

initTabs(document.querySelector('.content'));

let allOperations = [];
let selectedOp = null;

// ===== Load Operations =====
async function loadOperations() {
  const el = document.getElementById('ops-table');
  showLoading(el);
  try {
    const data = await api.get('/api/langfuse/openapi/operations');
    const result = data.data?.result || data.result || data;
    const ops = result.operations || [];
    const policy = result.policy || '-';
    const count = result.count ?? ops.length;
    allOperations = ops;

    document.getElementById('ops-summary').textContent =
      t('apiConsole.totalOps', { count }) + ' · ' + t('apiConsole.policyNote', { policy });

    renderOpsTable(ops);
  } catch (err) {
    showEmpty(el, err.message);
  }
}

function renderOpsTable(ops) {
  const el = document.getElementById('ops-table');
  if (ops.length === 0) {
    showEmpty(el, t('apiConsole.noOps'));
    return;
  }

  const methodBadge = (m) => {
    const cls = { GET: 'badge-success', POST: 'badge-info', PUT: 'badge-warning', PATCH: 'badge-warning', DELETE: 'badge-danger' };
    return `<span class="badge ${cls[m] || 'badge-default'}">${escapeHtml(m)}</span>`;
  };

  el.innerHTML = `
    <div class="table-wrap"><table>
      <thead><tr>
        <th>${t('apiConsole.operationId')}</th>
        <th>${t('apiConsole.method')}</th>
        <th>${t('apiConsole.path')}</th>
        <th>${t('apiConsole.summary')}</th>
        <th>${t('apiConsole.mutating')}</th>
        <th></th>
      </tr></thead>
      <tbody>
        ${ops.map(op => `
          <tr>
            <td class="td-mono text-sm">${escapeHtml(op.operation_id)}</td>
            <td>${methodBadge(op.method)}</td>
            <td class="td-mono text-sm">${escapeHtml(op.path)}</td>
            <td class="text-sm">${escapeHtml(op.summary || '-')}</td>
            <td>${op.mutating ? `<span class="badge badge-warning">${t('apiConsole.yes')}</span>` : `<span class="badge badge-default">${t('apiConsole.no')}</span>`}</td>
            <td><button class="btn btn-sm btn-primary exec-op" data-opid="${escapeHtml(op.operation_id)}">${t('apiConsole.execute')}</button></td>
          </tr>
        `).join('')}
      </tbody>
    </table></div>
  `;

  document.querySelectorAll('.exec-op').forEach(btn => {
    btn.addEventListener('click', () => {
      const op = allOperations.find(o => o.operation_id === btn.dataset.opid);
      if (op) selectOperation(op);
    });
  });
}

// ===== Filter =====
document.getElementById('ops-filter')?.addEventListener('input', (e) => {
  const q = e.target.value.toLowerCase();
  if (!q) {
    renderOpsTable(allOperations);
    return;
  }
  const filtered = allOperations.filter(op =>
    (op.operation_id || '').toLowerCase().includes(q) ||
    (op.path || '').toLowerCase().includes(q) ||
    (op.summary || '').toLowerCase().includes(q)
  );
  renderOpsTable(filtered);
});

// ===== Select Operation & Switch to Execute Tab =====
function selectOperation(op) {
  selectedOp = op;

  // Switch to execute tab
  document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
  document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
  document.querySelector('[data-tab="tab-execute"]').classList.add('active');
  document.getElementById('tab-execute').classList.add('active');

  // Fill form
  document.getElementById('exec-placeholder').style.display = 'none';
  document.getElementById('exec-form').style.display = '';
  document.getElementById('exec-op-id').textContent = op.operation_id;
  document.getElementById('exec-method-path').innerHTML =
    `<span class="badge ${op.method === 'GET' ? 'badge-success' : op.method === 'DELETE' ? 'badge-danger' : 'badge-info'}">${escapeHtml(op.method)}</span> <code>${escapeHtml(op.path)}</code>`;
  document.getElementById('exec-summary').textContent = op.summary || '-';

  // Path params
  const pathParamsDiv = document.getElementById('exec-path-params');
  const pathFieldsDiv = document.getElementById('exec-path-fields');
  const pathMatches = (op.path || '').match(/\{(\w+)\}/g) || [];
  if (pathMatches.length > 0) {
    pathParamsDiv.style.display = '';
    pathFieldsDiv.innerHTML = pathMatches.map(p => {
      const name = p.replace(/[{}]/g, '');
      return `<div class="form-group"><label class="form-label">${escapeHtml(name)}</label><input class="form-input path-param" data-name="${escapeHtml(name)}" placeholder="${escapeHtml(name)}" /></div>`;
    }).join('');
  } else {
    pathParamsDiv.style.display = 'none';
  }

  // Query params - show for GET requests
  const queryDiv = document.getElementById('exec-query-params');
  const queryFieldsDiv = document.getElementById('exec-query-fields');
  if (op.method === 'GET') {
    queryDiv.style.display = '';
    queryFieldsDiv.innerHTML = `<div class="form-group"><textarea class="form-input" id="exec-query-text" rows="2" style="font-family:var(--font-mono);font-size:13px" placeholder='{"key": "value"}'></textarea></div>`;
  } else {
    queryDiv.style.display = 'none';
  }

  // Request body - show for non-GET
  const bodyGroup = document.getElementById('exec-body-group');
  if (op.method !== 'GET') {
    bodyGroup.style.display = '';
    document.getElementById('exec-body').value = '';
  } else {
    bodyGroup.style.display = 'none';
  }

  // Reset response
  document.getElementById('exec-response-wrap').style.display = 'none';
  document.getElementById('exec-response').textContent = '';
}

// ===== Execute =====
document.getElementById('exec-btn')?.addEventListener('click', async () => {
  if (!selectedOp) return;

  const btn = document.getElementById('exec-btn');
  btn.disabled = true;
  btn.textContent = t('common.running');

  try {
    // Collect path params
    const pathParams = {};
    document.querySelectorAll('.path-param').forEach(input => {
      if (input.value) pathParams[input.dataset.name] = input.value;
    });

    // Collect query params
    let query = {};
    const queryText = document.getElementById('exec-query-text')?.value;
    if (queryText) {
      try { query = JSON.parse(queryText); } catch { query = {}; }
    }

    // Collect body
    let body = null;
    const bodyText = document.getElementById('exec-body')?.value;
    if (bodyText && selectedOp.method !== 'GET') {
      try { body = JSON.parse(bodyText); } catch { body = bodyText; }
    }

    const payload = {
      operation_id: selectedOp.operation_id,
      method: selectedOp.method,
      path: selectedOp.path,
      path_params: Object.keys(pathParams).length > 0 ? pathParams : undefined,
      query: Object.keys(query).length > 0 ? query : undefined,
      body: body,
    };

    const data = await api.post('/api/langfuse/openapi/execute', payload);

    document.getElementById('exec-response-wrap').style.display = '';
    document.getElementById('exec-response').textContent = JSON.stringify(data, null, 2);
    toast(t('apiConsole.executeSuccess'), 'success');
  } catch (err) {
    document.getElementById('exec-response-wrap').style.display = '';
    document.getElementById('exec-response').textContent = `Error: ${err.message}`;
    toast(t('apiConsole.executeError'), 'error');
  } finally {
    btn.disabled = false;
    btn.textContent = t('apiConsole.executeBtn');
  }
});

// Init
loadOperations();
</script>
{% endblock %}
