// ═══════════════════════════════════════════════════════
//  CVC Dashboard — Hive Memory Module
// ═══════════════════════════════════════════════════════
import * as api from './api';
import type { HiveMemoryEntry } from './types';

function esc(s: string): string {
  const d = document.createElement('div');
  d.textContent = s;
  return d.innerHTML;
}

function toast(message: string, type: 'success' | 'error' | 'info' = 'info'): void {
  (window as any).toast?.(message, type);
}

function formatDate(ts: number | string): string {
  try {
    const d = typeof ts === 'number' ? new Date(ts * 1000) : new Date(ts);
    return d.toLocaleString();
  } catch { return String(ts); }
}

// ── Category colors ─────────────────────────────────
const CATEGORY_COLORS: Record<string, string> = {
  insight: 'tag-blue',
  decision: 'tag-purple',
  discovery: 'tag-green',
  warning: 'tag-yellow',
  error: 'tag-red',
  task_result: 'tag-cyan',
  learning: 'tag-pink',
  general: '',
};

function categoryTag(cat: string): string {
  const cls = CATEGORY_COLORS[cat] || '';
  return `<span class="tag ${cls}">${esc(cat)}</span>`;
}

// ── Write to hive ───────────────────────────────────
function setupHiveWriter(): void {
  document.getElementById('hive-write-btn')?.addEventListener('click', async () => {
    const agentId = (document.getElementById('hive-write-agent') as HTMLInputElement)?.value.trim();
    const category = (document.getElementById('hive-write-category') as HTMLSelectElement)?.value || 'general';
    const tagsStr = (document.getElementById('hive-write-tags') as HTMLInputElement)?.value.trim();
    const content = (document.getElementById('hive-write-content') as HTMLTextAreaElement)?.value.trim();

    if (!agentId) { toast('Agent ID required', 'error'); return; }
    if (!content) { toast('Content required', 'error'); return; }

    const tags = tagsStr ? tagsStr.split(',').map(s => s.trim()).filter(Boolean) : [];

    try {
      await api.writeHiveMemory(agentId, content, category, tags);
      toast('Written to hive memory', 'success');
      // Clear
      (document.getElementById('hive-write-content') as HTMLTextAreaElement).value = '';
      (document.getElementById('hive-write-tags') as HTMLInputElement).value = '';
      loadHiveData();
    } catch (e) {
      toast((e as Error).message, 'error');
    }
  });
}

// ── Filter ──────────────────────────────────────────
function setupHiveFilters(): void {
  document.getElementById('hive-filter-btn')?.addEventListener('click', loadHiveFeed);

  document.getElementById('hive-compact-btn')?.addEventListener('click', async () => {
    try {
      const result = await api.compactHiveMemory();
      toast(result.message || 'Hive memory compacted', 'success');
      loadHiveData();
    } catch (e) { toast((e as Error).message, 'error'); }
  });
}

// ── Feed renderer ───────────────────────────────────
function renderEntry(e: HiveMemoryEntry): string {
  const tags = (e.tags || []).map(t => `<span class="tag tag-sm">${esc(t)}</span>`).join(' ');
  return `
    <div class="hive-entry" data-category="${esc(e.category)}">
      <div class="hive-entry-header">
        <span class="hive-entry-agent">🤖 ${esc(e.agent_id)}</span>
        ${categoryTag(e.category)}
        <span class="hive-entry-time">${formatDate(e.timestamp)}</span>
      </div>
      <div class="hive-entry-content">${esc(e.content)}</div>
      ${tags ? `<div class="hive-entry-tags">${tags}</div>` : ''}
      ${e.commit_hash ? `<div class="hive-entry-hash"><code>${esc(e.commit_hash.slice(0, 8))}</code></div>` : ''}
    </div>
  `;
}

async function loadHiveFeed(): Promise<void> {
  const el = document.getElementById('hive-memory-feed');
  if (!el) return;

  const category = (document.getElementById('hive-filter-category') as HTMLSelectElement)?.value || undefined;
  const agentId = (document.getElementById('hive-filter-agent') as HTMLInputElement)?.value.trim() || undefined;
  const query = (document.getElementById('hive-filter-query') as HTMLInputElement)?.value.trim() || undefined;

  try {
    const data = await api.getHiveMemory(query, category, agentId, 50);
    const entries = data.entries || [];
    if (!entries.length) {
      el.innerHTML = '<p class="text-muted">No hive memory entries yet. Write something to the hive above!</p>';
      return;
    }
    el.innerHTML = entries.map(renderEntry).join('');
  } catch {
    el.innerHTML = '<p class="text-muted">Failed to load hive memory.</p>';
  }
}

// ── Stats ───────────────────────────────────────────
async function loadHiveStats(): Promise<void> {
  try {
    const stats = await api.getHiveMemoryStats();
    const setText = (id: string, v: string | number) => {
      const e = document.getElementById(id);
      if (e) e.textContent = String(v);
    };
    setText('hive-mem-total', stats.total_entries);
    setText('hive-mem-agents', stats.agent_count);
    setText('hive-mem-categories', Object.keys(stats.categories || {}).length);
    setText('hive-mem-latest', stats.total_entries > 0 ? 'Active' : 'Empty');
  } catch { /* ignore */ }
}

// ── Summary context ─────────────────────────────────
async function loadHiveSummary(): Promise<void> {
  const el = document.getElementById('hive-summary-context');
  if (!el) return;
  try {
    const data = await api.getHiveMemorySummary(10);
    if (data.context) {
      el.innerHTML = `<pre class="hive-summary-pre">${esc(data.context)}</pre>`;
    } else {
      el.innerHTML = '<p class="text-muted">No summary available yet.</p>';
    }
  } catch {
    el.innerHTML = '<p class="text-muted">Failed to load summary.</p>';
  }
}

// ── Main loader ─────────────────────────────────────
export async function loadHiveData(): Promise<void> {
  await Promise.all([
    loadHiveStats(),
    loadHiveFeed(),
    loadHiveSummary(),
  ]);
}

// ── Init ────────────────────────────────────────────
export function initHive(): void {
  setupHiveWriter();
  setupHiveFilters();
}
