/**
 * Flynn Token Usage Page
 *
 * Shows per-session token usage breakdown including input/output tokens,
 * API calls, estimated cost, and delegation details.
 * Auto-refreshes every 30 seconds.
 */

let _timer = null;

function formatNumber(n) {
  return (n ?? 0).toLocaleString();
}

function formatCost(n) {
  if (!n || n === 0) {return '$0.00';}
  if (n < 0.01) {return `$${n.toFixed(4)}`;}
  return `$${n.toFixed(2)}`;
}

function truncateId(id) {
  if (!id) {return '-';}
  if (id.length <= 24) {return id;}
  return id.slice(0, 24) + '\u2026';
}

async function loadUsage(el, client) {
  let data;
  let contextData;

  try {
    data = await client.call('system.tokenUsage');
    contextData = await client.call('system.contextUsage');
  } catch (err) {
    el.innerHTML = `<div class="text-center py-12 px-6 text-zinc-500 text-sm">Failed to load usage: ${err.message}</div>`;
    return;
  }

  const sessions = data?.sessions ?? [];
  const contextBySession = new Map((contextData?.sessions ?? []).map(s => [s.sessionId, s.budget]));

  // Compute totals across all sessions
  let totalInput = 0;
  let totalOutput = 0;
  let totalCalls = 0;
  let totalCost = 0;

  for (const s of sessions) {
    totalInput += s.total?.inputTokens ?? 0;
    totalOutput += s.total?.outputTokens ?? 0;
    totalCalls += s.total?.calls ?? 0;
    totalCost += s.total?.estimatedCost ?? 0;
  }

  // Summary cards
  const summaryHtml = `
    <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-8">
      <div class="bg-zinc-900 border border-zinc-800 rounded-lg p-4 hover:border-zinc-600 transition-colors">
        <div class="text-xs font-medium text-zinc-400 uppercase tracking-wide mb-2">Total Input Tokens</div>
        <div class="text-2xl font-bold font-mono text-zinc-50">${formatNumber(totalInput)}</div>
      </div>
      <div class="bg-zinc-900 border border-zinc-800 rounded-lg p-4 hover:border-zinc-600 transition-colors">
        <div class="text-xs font-medium text-zinc-400 uppercase tracking-wide mb-2">Total Output Tokens</div>
        <div class="text-2xl font-bold font-mono text-zinc-50">${formatNumber(totalOutput)}</div>
      </div>
      <div class="bg-zinc-900 border border-zinc-800 rounded-lg p-4 hover:border-zinc-600 transition-colors">
        <div class="text-xs font-medium text-zinc-400 uppercase tracking-wide mb-2">Total Tokens</div>
        <div class="text-2xl font-bold font-mono text-zinc-50">${formatNumber(totalInput + totalOutput)}</div>
      </div>
      <div class="bg-zinc-900 border border-zinc-800 rounded-lg p-4 hover:border-zinc-600 transition-colors">
        <div class="text-xs font-medium text-zinc-400 uppercase tracking-wide mb-2">API Calls</div>
        <div class="text-2xl font-bold font-mono text-zinc-50">${formatNumber(totalCalls)}</div>
      </div>
      <div class="bg-zinc-900 border border-zinc-800 rounded-lg p-4 hover:border-zinc-600 transition-colors">
        <div class="text-xs font-medium text-zinc-400 uppercase tracking-wide mb-2">Estimated Cost</div>
        <div class="text-2xl font-bold font-mono text-zinc-50">${formatCost(totalCost)}</div>
      </div>
      <div class="bg-zinc-900 border border-zinc-800 rounded-lg p-4 hover:border-zinc-600 transition-colors">
        <div class="text-xs font-medium text-zinc-400 uppercase tracking-wide mb-2">Active Sessions</div>
        <div class="text-2xl font-bold font-mono text-zinc-50">${sessions.length}</div>
      </div>
    </div>
  `;

  // Per-session table
  let tableHtml = '';
  if (sessions.length === 0) {
    tableHtml = '<div class="text-center py-12 px-6 text-zinc-500 text-sm">No active sessions with usage data</div>';
  } else {
    const rows = sessions.map(s => {
      const inTok = s.total?.inputTokens ?? 0;
      const outTok = s.total?.outputTokens ?? 0;
      const calls = s.total?.calls ?? 0;
      const cost = s.total?.estimatedCost ?? 0;
      const budget = contextBySession.get(s.sessionId);
      const contextCell = budget
        ? `${budget.usagePct.toFixed(1)}% (${formatNumber(budget.estimatedTokens)}/${formatNumber(budget.contextWindow)})`
        : '<span class="text-zinc-500">-</span>';

      // Build delegation breakdown if present
      const delegationEntries = Object.entries(s.delegation ?? {});
      let delegationCell = '<span class="text-zinc-500">-</span>';
      if (delegationEntries.length > 0) {
        delegationCell = delegationEntries.map(([tier, stats]) =>
          `<span class="inline-block px-2 py-0.5 text-xs rounded-full font-semibold bg-green-500/15 text-green-500">${tier}</span> ${formatNumber(stats.inputTokens)}/${formatNumber(stats.outputTokens)}`,
        ).join('<br>');
      }

      return `
        <tr class="hover:bg-zinc-800/50">
          <td class="px-3 py-2 text-zinc-50 border-b border-zinc-800/50" title="${s.sessionId}">${truncateId(s.sessionId)}</td>
          <td class="px-3 py-2 text-zinc-50 border-b border-zinc-800/50">${formatNumber(inTok)}</td>
          <td class="px-3 py-2 text-zinc-50 border-b border-zinc-800/50">${formatNumber(outTok)}</td>
          <td class="px-3 py-2 text-zinc-50 border-b border-zinc-800/50">${formatNumber(inTok + outTok)}</td>
          <td class="px-3 py-2 text-zinc-50 border-b border-zinc-800/50">${formatNumber(calls)}</td>
          <td class="px-3 py-2 text-zinc-50 border-b border-zinc-800/50">${formatCost(cost)}</td>
          <td class="px-3 py-2 text-zinc-50 border-b border-zinc-800/50">${contextCell}</td>
          <td class="px-3 py-2 text-zinc-50 border-b border-zinc-800/50">${delegationCell}</td>
        </tr>
      `;
    }).join('');

    tableHtml = `
      <div class="overflow-x-auto">
        <table class="w-full text-sm">
          <thead>
            <tr>
              <th class="text-left px-3 py-2 text-xs font-medium text-zinc-400 uppercase tracking-wide border-b border-zinc-800">Session</th>
              <th class="text-left px-3 py-2 text-xs font-medium text-zinc-400 uppercase tracking-wide border-b border-zinc-800">Input</th>
              <th class="text-left px-3 py-2 text-xs font-medium text-zinc-400 uppercase tracking-wide border-b border-zinc-800">Output</th>
              <th class="text-left px-3 py-2 text-xs font-medium text-zinc-400 uppercase tracking-wide border-b border-zinc-800">Total</th>
              <th class="text-left px-3 py-2 text-xs font-medium text-zinc-400 uppercase tracking-wide border-b border-zinc-800">Calls</th>
              <th class="text-left px-3 py-2 text-xs font-medium text-zinc-400 uppercase tracking-wide border-b border-zinc-800">Cost</th>
              <th class="text-left px-3 py-2 text-xs font-medium text-zinc-400 uppercase tracking-wide border-b border-zinc-800">Context</th>
              <th class="text-left px-3 py-2 text-xs font-medium text-zinc-400 uppercase tracking-wide border-b border-zinc-800">Delegation</th>
            </tr>
          </thead>
          <tbody>
            ${rows}
          </tbody>
        </table>
      </div>
    `;
  }

  el.innerHTML = `
    <div class="flex items-center justify-between mb-6">
      <h1 class="text-2xl font-semibold text-zinc-50">Token Usage</h1>
      <button class="px-3 py-1.5 text-sm font-medium rounded-md border border-zinc-700 bg-zinc-800 text-zinc-200 hover:bg-zinc-700 transition-colors shrink-0" id="usage-refresh-btn">Refresh</button>
    </div>
    ${summaryHtml}
    <h2 class="text-lg font-semibold text-zinc-50 mb-4 mt-2 pb-2 border-b border-zinc-800">Per-Session Breakdown</h2>
    ${tableHtml}
  `;

  // Wire up refresh button
  const refreshBtn = el.querySelector('#usage-refresh-btn');
  if (refreshBtn) {
    refreshBtn.addEventListener('click', () => {
      loadUsage(el, client).catch(() => {});
    });
  }
}

export const UsagePage = {
  async render(el, client) {
    await loadUsage(el, client);

    // Auto-refresh every 30 seconds
    _timer = setInterval(() => {
      loadUsage(el, client).catch(() => {});
    }, 30000);
  },

  teardown() {
    if (_timer) {
      clearInterval(_timer);
      _timer = null;
    }
  },
};
