{% extends "base.html" %}

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

{% block content %}
<div class="tabs" id="settings-tabs">
  <button class="tab active" data-tab="tab-llm" data-i18n="settings.llmKeys">LLM Keys</button>
  <button class="tab" data-tab="tab-langfuse" data-i18n="settings.langfuse">Langfuse</button>
  <button class="tab" data-tab="tab-defaults" data-i18n="settings.defaults">Defaults</button>
  <button class="tab" data-tab="tab-integrations" data-i18n="settings.integrations">Integrations</button>
  <button class="tab" data-tab="tab-validate" data-i18n="settings.validate">Validate</button>
</div>

<!-- LLM Keys -->
<div class="tab-panel active" id="tab-llm">
  <div class="card">
    <div class="card-header">
      <div class="card-title" data-i18n="settings.llmApiKeys">LLM API Keys</div>
      <div id="llm-status" class="flex gap-8"></div>
    </div>
    <form id="llm-form">
      <div class="form-group">
        <label class="form-label" data-i18n="settings.saveTarget">Save Target</label>
        <select class="form-select" id="llm-target" style="max-width:200px">
          <option value="project" data-i18n="settings.projectEnv">Project .env</option>
          <option value="home" data-i18n="settings.homeEnv">Home .env</option>
        </select>
      </div>
      <div class="form-row">
        <div class="form-group"><label class="form-label">OPENAI_API_KEY</label><input class="form-input" id="llm-openai" type="password" placeholder="sk-..." /></div>
        <div class="form-group"><label class="form-label">ANTHROPIC_API_KEY</label><input class="form-input" id="llm-anthropic" type="password" placeholder="sk-ant-..." /></div>
      </div>
      <div class="form-row">
        <div class="form-group"><label class="form-label">GOOGLE_API_KEY</label><input class="form-input" id="llm-google" type="password" placeholder="AIza..." /></div>
        <div class="form-group"><label class="form-label">GEMINI_API_KEY</label><input class="form-input" id="llm-gemini" type="password" placeholder="AIza..." /></div>
      </div>
      <div class="form-row">
        <div class="form-group"><label class="form-label">OPENROUTER_API_KEY</label><input class="form-input" id="llm-openrouter" type="password" placeholder="sk-or-v1-..." /></div>
        <div class="form-group"><label class="form-label">OPENROUTER_BASE_URL</label><input class="form-input" id="llm-openrouter-url" type="text" placeholder="https://openrouter.ai/api/v1" /></div>
      </div>
      <h4 class="mt-16 mb-8" data-i18n="settings.localInference">Local Inference Servers</h4>
      <div class="form-row">
        <div class="form-group"><label class="form-label" data-i18n="settings.ollamaBaseUrl">Ollama Base URL</label><input class="form-input" id="llm-ollama-url" type="text" placeholder="http://localhost:11434" /></div>
        <div class="form-group"><label class="form-label" data-i18n="settings.vllmBaseUrl">vLLM Base URL</label><input class="form-input" id="llm-vllm-url" type="text" placeholder="http://localhost:8000" /></div>
      </div>
      <div class="form-row">
        <div class="form-group"><label class="form-label" data-i18n="settings.lmstudioBaseUrl">LM Studio Base URL</label><input class="form-input" id="llm-lmstudio-url" type="text" placeholder="http://localhost:1234" /></div>
        <div class="form-group"></div>
      </div>
      <button class="btn btn-primary" type="submit" data-i18n="settings.saveKeys">Save Keys</button>
    </form>
    <div id="llm-result" class="pre-wrap mt-16 hidden"></div>
  </div>
</div>

<!-- Langfuse Projects -->
<div class="tab-panel" id="tab-langfuse">
  <div class="card">
    <div class="card-header">
      <div class="card-title" data-i18n="settings.langfuseProjects">Langfuse Projects</div>
      <button class="btn btn-sm btn-primary" id="btn-add-project" data-i18n="settings.addProject">+ Add Project</button>
    </div>
    <p class="text-muted mb-16" data-i18n="settings.langfuseProjectsDesc">Manage multiple Langfuse project connections per user.</p>
    <div id="lf-projects-list">
      <div class="loading-center"><div class="spinner"></div></div>
    </div>
    <div id="lf-result" class="pre-wrap mt-16 hidden"></div>
  </div>

  <!-- Project Modal -->
  <div id="project-modal" class="modal-overlay hidden">
    <div class="card" style="max-width:520px;margin:10vh auto;">
      <div class="card-title mb-16" id="project-modal-title" data-i18n="settings.addProject">Add Project</div>
      <form id="project-form">
        <input type="hidden" id="pf-id" value="" />
        <div class="form-group"><label class="form-label" data-i18n="settings.projectName">Name</label><input class="form-input" id="pf-name" placeholder="Production" required /></div>
        <div class="form-group"><label class="form-label" data-i18n="settings.baseUrl">Base URL</label><input class="form-input" id="pf-url" placeholder="https://cloud.langfuse.com" /></div>
        <div class="form-row">
          <div class="form-group"><label class="form-label" data-i18n="settings.publicKey">Public Key</label><input class="form-input" id="pf-pk" type="password" placeholder="pk-lf-..." /></div>
          <div class="form-group"><label class="form-label" data-i18n="settings.secretKey">Secret Key</label><input class="form-input" id="pf-sk" type="password" placeholder="sk-lf-..." /></div>
        </div>
        <div class="form-group"><label class="form-label" data-i18n="settings.environment">Environment</label>
          <select class="form-select" id="pf-env" style="max-width:200px">
            <option value="" data-i18n="settings.default">Default</option>
            <option value="prod" data-i18n="settings.production">Production</option>
            <option value="staging" data-i18n="settings.staging">Staging</option>
            <option value="dev" data-i18n="settings.development">Development</option>
          </select>
        </div>
        <div class="form-group"><label class="form-label"><input type="checkbox" id="pf-default" /> <span data-i18n="settings.setAsDefault">Set as default</span></label></div>
        <div class="flex gap-8">
          <button class="btn btn-primary" type="submit" id="pf-submit-btn" data-i18n="common.save">Save</button>
          <button class="btn btn-secondary" type="button" id="pf-cancel-btn" data-i18n="common.cancel">Cancel</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Defaults -->
<div class="tab-panel" id="tab-defaults">
  <div class="card">
    <div class="card-title mb-16" data-i18n="settings.defaultSettings">Default Settings</div>
    <form id="defaults-form">
      <div class="form-group"><label class="form-label" data-i18n="settings.saveTarget">Save Target</label>
        <select class="form-select" id="df-target" style="max-width:200px">
          <option value="project" data-i18n="settings.project">Project</option>
          <option value="home" data-i18n="settings.home">Home</option>
        </select>
      </div>
      <div class="form-row">
        <div class="form-group"><label class="form-label" data-i18n="settings.defaultMode">Default Mode</label>
          <select class="form-select" id="df-mode">
            <option value="overview" data-i18n="settings.overview">Overview</option>
            <option value="observability" data-i18n="settings.observability">Observability</option>
            <option value="prompt" data-i18n="settings.prompt">Prompt</option>
            <option value="evaluation" data-i18n="settings.evaluation">Evaluation</option>
          </select>
        </div>
        <div class="form-group"><label class="form-label" data-i18n="settings.defaultLimit">Default Limit</label><input class="form-input" id="df-limit" type="number" value="20" min="1" max="100" /></div>
      </div>
      <div class="form-row">
        <div class="form-group"><label class="form-label" data-i18n="settings.timezone">Timezone</label><input class="form-input" id="df-tz" value="UTC" /></div>
        <div class="form-group"><label class="form-label" data-i18n="settings.retentionDays">Retention Days</label><input class="form-input" id="df-ret" type="number" value="30" min="1" max="3650" /></div>
      </div>
      <div class="form-group">
        <label class="form-label"><input type="checkbox" id="df-compare" /> <span data-i18n="settings.enableCompareModels">Enable Compare Models by Default</span></label>
      </div>
      <div class="form-group">
        <label class="form-label" data-i18n="settings.reportSummaryModel">Report Summary Model</label>
        <select class="form-select" id="df-report-model">
          <option value="" data-i18n="settings.autoFallback">Auto (Fallback)</option>
        </select>
      </div>
      <button class="btn btn-primary" type="submit" data-i18n="settings.saveDefaults">Save Defaults</button>
    </form>
  </div>
</div>

<!-- Integrations -->
<div class="tab-panel" id="tab-integrations">
  <div class="card">
    <div class="card-title mb-16" data-i18n="settings.integrations">Integrations</div>
    <form id="int-form">
      <div class="form-group"><label class="form-label" data-i18n="settings.saveTarget">Save Target</label>
        <select class="form-select" id="int-target" style="max-width:200px">
          <option value="project" data-i18n="settings.project">Project</option>
          <option value="home" data-i18n="settings.home">Home</option>
        </select>
      </div>
      <div class="form-group"><label class="form-label" data-i18n="settings.slackWebhookUrl">Slack Webhook URL</label><input class="form-input" id="int-slack" placeholder="https://hooks.slack.com/..." /></div>
      <div class="form-group"><label class="form-label" data-i18n="settings.webhookUrl">Webhook URL</label><input class="form-input" id="int-webhook" placeholder="https://..." /></div>
      <div class="form-group"><label class="form-label" data-i18n="settings.emailRecipients">Email Recipients (comma separated)</label><input class="form-input" id="int-email" placeholder="admin@example.com" /></div>
      <div class="form-group"><label class="form-label"><input type="checkbox" id="int-enabled" /> <span data-i18n="settings.enableIntegrations">Enable Integrations</span></label></div>
      <button class="btn btn-primary" type="submit" data-i18n="settings.saveIntegrations">Save Integrations</button>
    </form>
  </div>
</div>

<!-- Validate -->
<div class="tab-panel" id="tab-validate">
  <div class="card">
    <div class="card-title mb-16" data-i18n="settings.validateConfiguration">Validate Configuration</div>
    <div class="flex gap-8 mb-16">
      <button class="btn btn-primary" id="btn-validate" data-i18n="settings.runValidation">Run Validation</button>
      <button class="btn btn-secondary" id="btn-secrets-status" data-i18n="settings.checkSecretsStatus">Check Secrets Status</button>
    </div>
    <div id="validate-result" class="pre-wrap hidden"></div>
  </div>
</div>
{% endblock %}

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

// Init tabs
initTabs(document.getElementById('settings-tabs')?.parentElement || document.querySelector('.content'));

// Load LLM key status
async function loadLLMStatus() {
  try {
    const data = await api.get('/api/settings/llm-keys');
    const el = document.getElementById('llm-status');
    const status = data.status || {};
    el.innerHTML = Object.entries(status).map(([k, v]) =>
      statusBadge(v ? 'set' : 'missing').replace('</span>', ` ${k}</span>`)
    ).join('');
  } catch {}
}

// LLM form
document.getElementById('llm-form')?.addEventListener('submit', async (e) => {
  e.preventDefault();
  const result = document.getElementById('llm-result');
  try {
    const data = await api.post('/api/settings/llm-keys', {
      target: document.getElementById('llm-target').value,
      openai_api_key: document.getElementById('llm-openai').value,
      anthropic_api_key: document.getElementById('llm-anthropic').value,
      google_api_key: document.getElementById('llm-google').value,
      gemini_api_key: document.getElementById('llm-gemini').value,
      openrouter_api_key: document.getElementById('llm-openrouter').value,
      openrouter_base_url: document.getElementById('llm-openrouter-url').value,
      ollama_base_url: document.getElementById('llm-ollama-url').value,
      vllm_base_url: document.getElementById('llm-vllm-url').value,
      lmstudio_base_url: document.getElementById('llm-lmstudio-url').value,
    });
    result.classList.remove('hidden');
    result.textContent = JSON.stringify(data, null, 2);
    toast(t('settings.keysSaved'), 'success');
    loadLLMStatus();
  } catch (err) {
    result.classList.remove('hidden');
    result.textContent = `${t('common.error')}: ${err.message}`;
    toast(err.message, 'error');
  }
});

// ---------------------------------------------------------------------------
// Langfuse Projects CRUD
// ---------------------------------------------------------------------------
const projectsList = document.getElementById('lf-projects-list');
const projectModal = document.getElementById('project-modal');
const projectForm = document.getElementById('project-form');
const pfId = document.getElementById('pf-id');

function renderProjectCard(p) {
  const star = p.is_default ? '★ ' : '';
  const defaultBadge = p.is_default
    ? `<span class="badge badge-accent" style="font-size:0.75rem">${t('settings.default')}</span>`
    : '';
  const envLabel = p.environment || '';
  return `
    <div class="card mb-8" style="padding:12px 16px">
      <div class="flex" style="justify-content:space-between;align-items:center">
        <div>
          <strong>${star}${escapeHtml(p.name)}</strong> ${defaultBadge}
          <div class="text-muted" style="font-size:0.85rem">${escapeHtml(p.base_url || '—')}${envLabel ? ' · ' + escapeHtml(envLabel) : ''}</div>
          <div class="text-muted" style="font-size:0.8rem">PK: ${escapeHtml(p.public_key_masked || '—')} · SK: ${escapeHtml(p.secret_key_masked || '—')}</div>
        </div>
        <div class="flex gap-8">
          <button class="btn btn-sm btn-secondary" onclick="window._lfEditProject(${p.id})" data-i18n="common.edit">${t('common.edit')}</button>
          ${!p.is_default ? `<button class="btn btn-sm btn-secondary" onclick="window._lfSetDefault(${p.id})" data-i18n="settings.setAsDefault">${t('settings.setAsDefault')}</button>` : ''}
          <button class="btn btn-sm btn-danger" onclick="window._lfDeleteProject(${p.id})">${t('common.delete')}</button>
        </div>
      </div>
    </div>`;
}

let _projectsCache = [];

async function loadProjects() {
  try {
    const data = await api.get('/api/users/me/langfuse-projects');
    _projectsCache = data.data || [];
    if (_projectsCache.length === 0) {
      projectsList.innerHTML = `<p class="text-muted">${t('settings.noProjects')}</p>`;
    } else {
      projectsList.innerHTML = _projectsCache.map(renderProjectCard).join('');
    }
  } catch (err) {
    projectsList.innerHTML = `<p class="text-muted">${t('common.error')}: ${escapeHtml(err.message)}</p>`;
  }
}

function openProjectModal(project) {
  const title = document.getElementById('project-modal-title');
  if (project) {
    title.textContent = t('settings.editProject');
    pfId.value = project.id;
    document.getElementById('pf-name').value = project.name || '';
    document.getElementById('pf-url').value = project.base_url || '';
    document.getElementById('pf-pk').value = '';
    document.getElementById('pf-sk').value = '';
    document.getElementById('pf-env').value = project.environment || '';
    document.getElementById('pf-default').checked = project.is_default || false;
  } else {
    title.textContent = t('settings.addProject');
    pfId.value = '';
    projectForm.reset();
  }
  projectModal.classList.remove('hidden');
}

function closeProjectModal() {
  projectModal.classList.add('hidden');
  projectForm.reset();
  pfId.value = '';
}

document.getElementById('btn-add-project')?.addEventListener('click', () => openProjectModal(null));
document.getElementById('pf-cancel-btn')?.addEventListener('click', closeProjectModal);
projectModal?.addEventListener('click', (e) => { if (e.target === projectModal) closeProjectModal(); });

projectForm?.addEventListener('submit', async (e) => {
  e.preventDefault();
  const id = pfId.value;
  const body = {
    name: document.getElementById('pf-name').value.trim(),
    base_url: document.getElementById('pf-url').value.trim(),
    public_key: document.getElementById('pf-pk').value.trim(),
    secret_key: document.getElementById('pf-sk').value.trim(),
    environment: document.getElementById('pf-env').value,
    is_default: document.getElementById('pf-default').checked,
  };
  try {
    if (id) {
      const update = {};
      for (const [k, v] of Object.entries(body)) { if (v !== '' && v !== false) update[k] = v; }
      await api.put(`/api/users/me/langfuse-projects/${id}`, update);
      toast(t('settings.projectUpdated'), 'success');
    } else {
      await api.post('/api/users/me/langfuse-projects', body);
      toast(t('settings.projectCreated'), 'success');
    }
    closeProjectModal();
    loadProjects();
  } catch (err) {
    toast(err.message, 'error');
  }
});

window._lfEditProject = (id) => {
  const p = _projectsCache.find(x => x.id === id);
  if (p) openProjectModal(p);
};

window._lfSetDefault = async (id) => {
  try {
    await api.put(`/api/users/me/langfuse-projects/${id}/default`, {});
    toast(t('settings.defaultUpdated'), 'success');
    loadProjects();
  } catch (err) { toast(err.message, 'error'); }
};

window._lfDeleteProject = async (id) => {
  if (!confirm(t('settings.deleteProjectConfirm'))) return;
  try {
    await api.del(`/api/users/me/langfuse-projects/${id}`);
    toast(t('settings.projectDeleted'), 'success');
    loadProjects();
  } catch (err) { toast(err.message, 'error'); }
};

// Load report summary models dropdown
async function loadReportModels() {
  try {
    const data = await api.get('/api/models/available');
    const sel = document.getElementById('df-report-model');
    const groups = data.groups || [];
    groups.forEach(g => {
      const optgroup = document.createElement('optgroup');
      optgroup.label = g.provider.toUpperCase();
      g.models.forEach(m => {
        const opt = document.createElement('option');
        opt.value = g.provider + ':' + m.id;
        opt.textContent = m.label || m.id;
        optgroup.appendChild(opt);
      });
      sel.appendChild(optgroup);
    });
  } catch (err) {
    console.warn('Failed to load report models:', err);
  }
}

// Defaults form
document.getElementById('defaults-form')?.addEventListener('submit', async (e) => {
  e.preventDefault();
  try {
    await api.put('/api/settings/defaults', {
      target: document.getElementById('df-target').value,
      default_mode: document.getElementById('df-mode').value,
      default_limit: parseInt(document.getElementById('df-limit').value),
      timezone: document.getElementById('df-tz').value,
      retention_days: parseInt(document.getElementById('df-ret').value),
      default_compare_models: document.getElementById('df-compare').checked,
      report_summary_model: document.getElementById('df-report-model').value,
    });
    toast(t('settings.defaultsSaved'), 'success');
  } catch (err) { toast(err.message, 'error'); }
});

// Load defaults
async function loadDefaults() {
  try {
    const data = await api.get('/api/settings/defaults');
    const s = data.settings || data;
    if (s.default_mode) document.getElementById('df-mode').value = s.default_mode;
    if (s.default_limit) document.getElementById('df-limit').value = s.default_limit;
    if (s.timezone) document.getElementById('df-tz').value = s.timezone;
    if (s.retention_days) document.getElementById('df-ret').value = s.retention_days;
    if (s.default_compare_models) document.getElementById('df-compare').checked = true;
    if (s.report_summary_model) document.getElementById('df-report-model').value = s.report_summary_model;
  } catch {}
}

// Integrations form
document.getElementById('int-form')?.addEventListener('submit', async (e) => {
  e.preventDefault();
  try {
    await api.put('/api/settings/integrations', {
      target: document.getElementById('int-target').value,
      slack_webhook: document.getElementById('int-slack').value,
      webhook_url: document.getElementById('int-webhook').value,
      email_recipients: document.getElementById('int-email').value.split(',').map(s=>s.trim()).filter(Boolean),
      enabled: document.getElementById('int-enabled').checked,
    });
    toast(t('settings.integrationsSaved'), 'success');
  } catch (err) { toast(err.message, 'error'); }
});

// Load integrations
async function loadIntegrations() {
  try {
    const data = await api.get('/api/settings/integrations');
    const s = data.settings || data;
    if (s.slack_webhook) document.getElementById('int-slack').value = s.slack_webhook;
    if (s.webhook_url) document.getElementById('int-webhook').value = s.webhook_url;
    if (s.email_recipients) document.getElementById('int-email').value = (s.email_recipients || []).join(', ');
    if (s.enabled) document.getElementById('int-enabled').checked = true;
  } catch {}
}

// Validate
document.getElementById('btn-validate')?.addEventListener('click', async () => {
  const el = document.getElementById('validate-result');
  el.classList.remove('hidden');
  el.textContent = t('settings.validating');
  try {
    const data = await api.get('/api/langfuse/control/status');
    el.textContent = JSON.stringify(data, null, 2);
    toast(t('settings.validationComplete'), 'success');
  } catch (err) {
    el.textContent = `${t('common.error')}: ${err.message}`;
    toast(err.message, 'error');
  }
});

// Secrets status — show all projects connection info
document.getElementById('btn-secrets-status')?.addEventListener('click', async () => {
  const el = document.getElementById('validate-result');
  el.classList.remove('hidden');
  el.textContent = t('settings.checking');
  try {
    const data = await api.get('/api/users/me/langfuse-projects');
    const projects = data.data || [];
    const result = {
      ok: true,
      total_projects: projects.length,
      projects: projects.map(p => ({
        name: p.name,
        connected: Boolean(p.base_url && p.public_key_masked && p.secret_key_masked),
        base_url: p.base_url || '',
        public_key_masked: p.public_key_masked || '',
        secret_key_masked: p.secret_key_masked || '',
        environment: p.environment || '',
        is_default: p.is_default,
      })),
    };
    el.textContent = JSON.stringify(result, null, 2);
  } catch (err) {
    el.textContent = `${t('common.error')}: ${err.message}`;
  }
});

// Init
loadLLMStatus();
loadProjects();
loadReportModels().then(() => loadDefaults());
loadIntegrations();
</script>
{% endblock %}
