{% extends "base.html" %}

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

{% block topbar_actions %}
<button class="btn btn-sm btn-primary" id="btn-new-prompt" data-i18n="prompts.newPrompt">+ New Prompt</button>
{% endblock %}

{% block content %}
<div class="card">
  <div class="card-header">
    <div>
      <div class="card-title" data-i18n="prompts.promptManagement">Prompt Management</div>
      <div class="card-subtitle" data-i18n="prompts.promptManagementDesc">Manage Langfuse prompts and promote versions</div>
    </div>
    <button class="btn btn-sm btn-secondary" id="btn-refresh" data-i18n="common.refresh">Refresh</button>
  </div>
  <div id="prompts-list">
    <div class="loading-center"><div class="spinner"></div></div>
  </div>
</div>

<div class="card mt-20 hidden" id="prompt-detail-panel">
  <div class="card-header">
    <div class="card-title" id="prompt-detail-name" data-i18n="prompts.promptDetail">Prompt Detail</div>
    <div class="btn-group">
      <button class="btn btn-sm btn-success" id="btn-promote" data-i18n="prompts.promoteLabel">Promote Label</button>
      <button class="btn btn-sm btn-secondary" id="btn-close-prompt" data-i18n="common.close">Close</button>
    </div>
  </div>
  <div id="prompt-detail-content"></div>
</div>
{% endblock %}

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

let currentPromptName = null;

async function loadPrompts() {
  const el = document.getElementById('prompts-list');
  showLoading(el);

  try {
    const data = await api.get('/api/langfuse/prompts');
    const items = data.prompts || data.items || data || [];
    if (!Array.isArray(items) || items.length === 0) {
      showEmpty(el, t('prompts.noPromptsFound'));
      return;
    }
    el.innerHTML = `
      <div class="table-wrap">
        <table>
          <thead><tr><th>${t('common.name')}</th><th>${t('common.type')}</th><th>${t('prompts.labels')}</th><th>${t('common.tags')}</th><th>${t('common.actions')}</th></tr></thead>
          <tbody>
            ${items.map(p => `
              <tr>
                <td><a href="#" class="view-prompt" data-name="${escapeHtml(p.name)}">${escapeHtml(p.name)}</a></td>
                <td><span class="badge badge-default">${escapeHtml(p.type || 'text')}</span></td>
                <td>${(p.labels||[]).map(l => `<span class="badge badge-accent">${escapeHtml(l)}</span>`).join(' ') || '-'}</td>
                <td>${(p.tags||[]).map(tg => `<span class="tag">${escapeHtml(tg)}</span>`).join(' ') || '-'}</td>
                <td class="td-actions">
                  <button class="btn btn-sm btn-ghost view-prompt" data-name="${escapeHtml(p.name)}">${t('common.view')}</button>
                  <button class="btn btn-sm btn-ghost edit-prompt" data-name="${escapeHtml(p.name)}">${t('common.edit')}</button>
                  <button class="btn btn-sm btn-danger del-prompt" data-name="${escapeHtml(p.name)}">${t('common.delete')}</button>
                </td>
              </tr>
            `).join('')}
          </tbody>
        </table>
      </div>
    `;
    bindEvents();
  } catch (err) {
    showEmpty(el, `${t('common.error')}: ${err.message}`);
  }
}

function bindEvents() {
  document.querySelectorAll('.view-prompt').forEach(el => {
    el.addEventListener('click', (e) => { e.preventDefault(); viewPrompt(el.dataset.name); });
  });
  document.querySelectorAll('.edit-prompt').forEach(el => {
    el.addEventListener('click', () => editPrompt(el.dataset.name));
  });
  document.querySelectorAll('.del-prompt').forEach(el => {
    el.addEventListener('click', () => deletePrompt(el.dataset.name));
  });
}

async function viewPrompt(name) {
  currentPromptName = name;
  const panel = document.getElementById('prompt-detail-panel');
  const content = document.getElementById('prompt-detail-content');
  panel.classList.remove('hidden');
  showLoading(content);
  document.getElementById('prompt-detail-name').textContent = name;

  try {
    const data = await api.get(`/api/langfuse/prompts?name=${encodeURIComponent(name)}`);
    const p = data.prompt || data;
    const promptText = typeof p.prompt === 'string' ? p.prompt : JSON.stringify(p.prompt, null, 2);

    content.innerHTML = `
      <div class="detail-row"><div class="detail-label">${t('common.name')}</div><div class="detail-value">${escapeHtml(p.name)}</div></div>
      <div class="detail-row"><div class="detail-label">${t('common.type')}</div><div class="detail-value">${escapeHtml(p.type || 'text')}</div></div>
      <div class="detail-row"><div class="detail-label">${t('prompts.labels')}</div><div class="detail-value">${(p.labels||[]).map(l=>`<span class="badge badge-accent">${escapeHtml(l)}</span>`).join(' ')||'-'}</div></div>
      <div class="detail-row"><div class="detail-label">${t('common.tags')}</div><div class="detail-value">${(p.tags||[]).map(tg=>`<span class="tag">${escapeHtml(tg)}</span>`).join(' ')||'-'}</div></div>
      <div class="section-title mt-16">${t('prompts.promptContent')}</div>
      <div class="pre-wrap">${escapeHtml(promptText)}</div>
      ${p.config && Object.keys(p.config).length > 0 ? `
        <div class="section-title mt-16">${t('prompts.config')}</div>
        <div class="pre-wrap">${escapeHtml(JSON.stringify(p.config, null, 2))}</div>
      ` : ''}
    `;
    panel.scrollIntoView({ behavior: 'smooth' });
  } catch (err) {
    content.innerHTML = `<p class="text-muted">${err.message}</p>`;
  }
}

function editPrompt(name) {
  openModal(`${t('prompts.editPrompt')}: ${name}`, `
    <form id="edit-prompt-form">
      <div class="form-group"><label class="form-label">${t('prompts.promptContent')}</label>
        <textarea class="form-textarea" id="ep-content" rows="8" placeholder="${t('prompts.enterPromptText')}"></textarea>
      </div>
      <div class="form-row">
        <div class="form-group"><label class="form-label">${t('prompts.labelsComma')}</label><input class="form-input" id="ep-labels" /></div>
        <div class="form-group"><label class="form-label">${t('prompts.tagsComma')}</label><input class="form-input" id="ep-tags" /></div>
      </div>
      <div class="form-group"><label class="form-label">${t('prompts.commitMessage')}</label><input class="form-input" id="ep-commit" placeholder="${t('prompts.updatePrompt')}" /></div>
      <div class="modal-footer" style="padding:12px 0 0"><button type="submit" class="btn btn-primary">${t('common.update')}</button></div>
    </form>
  `);
  document.getElementById('edit-prompt-form')?.addEventListener('submit', async (e) => {
    e.preventDefault();
    try {
      const body = { commit_message: document.getElementById('ep-commit').value };
      const content = document.getElementById('ep-content').value;
      if (content) body.prompt = content;
      const labels = document.getElementById('ep-labels').value;
      if (labels) body.labels = labels.split(',').map(s=>s.trim()).filter(Boolean);
      const tags = document.getElementById('ep-tags').value;
      if (tags) body.tags = tags.split(',').map(s=>s.trim()).filter(Boolean);
      await api.patch(`/api/langfuse/prompts/${encodeURIComponent(name)}`, body);
      closeModal(); toast(t('prompts.promptUpdated'), 'success'); loadPrompts();
    } catch (err) { toast(err.message, 'error'); }
  });
}

async function deletePrompt(name) {
  if (!confirm(t('prompts.deleteConfirm').replace('{name}', name))) return;
  try { await api.del(`/api/langfuse/prompts/${encodeURIComponent(name)}`); toast(t('prompts.promptDeleted'), 'success'); loadPrompts(); }
  catch (err) { toast(err.message, 'error'); }
}

// New prompt
document.getElementById('btn-new-prompt')?.addEventListener('click', () => {
  openModal(t('prompts.createPrompt'), `
    <form id="new-prompt-form">
      <div class="form-group"><label class="form-label">${t('common.name')}</label><input class="form-input" id="np-name" required placeholder="${t('prompts.myPrompt')}" /></div>
      <div class="form-group"><label class="form-label">${t('prompts.promptContent')}</label>
        <textarea class="form-textarea" id="np-content" rows="6" required placeholder="${t('prompts.helpfulAssistant')}"></textarea>
      </div>
      <div class="form-row">
        <div class="form-group"><label class="form-label">${t('common.type')}</label>
          <select class="form-select" id="np-type"><option value="text">${t('prompts.text')}</option><option value="chat">${t('dashboard.chat')}</option></select>
        </div>
        <div class="form-group"><label class="form-label">${t('prompts.labels')}</label><input class="form-input" id="np-labels" placeholder="${t('prompts.productionLatest')}" /></div>
      </div>
      <div class="form-group"><label class="form-label">${t('common.tags')}</label><input class="form-input" id="np-tags" placeholder="${t('prompts.v1Experimental')}" /></div>
      <div class="modal-footer" style="padding:12px 0 0"><button type="submit" class="btn btn-primary">${t('common.create')}</button></div>
    </form>
  `);
  document.getElementById('new-prompt-form')?.addEventListener('submit', async (e) => {
    e.preventDefault();
    try {
      await api.post('/api/langfuse/prompts', {
        name: document.getElementById('np-name').value,
        prompt: document.getElementById('np-content').value,
        type: document.getElementById('np-type').value,
        labels: document.getElementById('np-labels').value.split(',').map(s=>s.trim()).filter(Boolean),
        tags: document.getElementById('np-tags').value.split(',').map(s=>s.trim()).filter(Boolean),
      });
      closeModal(); toast(t('prompts.promptCreated'), 'success'); loadPrompts();
    } catch (err) { toast(err.message, 'error'); }
  });
});

// Promote label
document.getElementById('btn-promote')?.addEventListener('click', () => {
  if (!currentPromptName) return;
  openModal(t('prompts.promoteLabel'), `
    <form id="promote-form">
      <div class="form-group"><label class="form-label">${t('prompts.label')}</label><input class="form-input" id="pl-label" required placeholder="production" /></div>
      <div class="form-group"><label class="form-label">${t('prompts.versionOptional')}</label><input class="form-input" id="pl-version" type="number" placeholder="e.g. 3" /></div>
      <div class="modal-footer" style="padding:12px 0 0"><button type="submit" class="btn btn-success">${t('prompts.promote')}</button></div>
    </form>
  `);
  document.getElementById('promote-form')?.addEventListener('submit', async (e) => {
    e.preventDefault();
    try {
      const body = { label: document.getElementById('pl-label').value };
      const ver = document.getElementById('pl-version').value;
      if (ver) body.version = parseInt(ver);
      await api.post(`/api/langfuse/prompts/${encodeURIComponent(currentPromptName)}/promote-label`, body);
      closeModal(); toast(t('prompts.labelPromoted'), 'success'); viewPrompt(currentPromptName);
    } catch (err) { toast(err.message, 'error'); }
  });
});

document.getElementById('btn-close-prompt')?.addEventListener('click', () => {
  document.getElementById('prompt-detail-panel').classList.add('hidden');
});
document.getElementById('btn-refresh')?.addEventListener('click', loadPrompts);

loadPrompts();
</script>
{% endblock %}
