import { AdminShell, EmptyState, StatCard, StatusPill } from '../components/admin/admin-page.jsx';
import { getState } from '@/lib/runtime.js';
import { getDb } from '@/lib/db.js';

export const dynamic = 'force-dynamic';
export const runtime = 'nodejs';

function getRecentEgress(limit = 100) {
  try {
    const db = getDb();
    return db.prepare(
      'SELECT * FROM tool_egress ORDER BY at DESC LIMIT ?'
    ).all(limit);
  } catch {
    return [];
  }
}

function getAuditSummary(limit = 12) {
  try {
    const db = getDb();
    return db.prepare(
      'SELECT type, COUNT(*) AS c FROM audit_logs GROUP BY type ORDER BY c DESC LIMIT ?'
    ).all(limit);
  } catch {
    return [];
  }
}

function getVoiceToolCalls(limit = 20) {
  try {
    const db = getDb();
    return db.prepare(
      'SELECT id, session_id, call_id, tool_name, status, latency_ms, created_at FROM voice_tool_calls ORDER BY created_at DESC LIMIT ?'
    ).all(limit);
  } catch {
    return [];
  }
}

function getDbStats() {
  try {
    const db = getDb();
    const pageCount = db.prepare('PRAGMA page_count').get();
    const pageSize = db.prepare('PRAGMA page_size').get();
    const bytes = (pageCount?.page_count || 0) * (pageSize?.page_size || 0);
    return { bytes };
  } catch {
    return { bytes: 0 };
  }
}

function formatBytes(n) {
  if (!n || n === 0) return '0 B';
  if (n < 1024) return `${n} B`;
  if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
  if (n < 1024 * 1024 * 1024) return `${(n / (1024 * 1024)).toFixed(1)} MB`;
  return `${(n / (1024 * 1024 * 1024)).toFixed(2)} GB`;
}

function statusTone(code, error) {
  if (error) return 'danger';
  if (!code) return 'neutral';
  if (code >= 200 && code < 300) return 'ready';
  if (code >= 300 && code < 400) return 'warn';
  return 'danger';
}

function runStatusTone(status) {
  if (!status) return 'neutral';
  if (status === 'complete' || status === 'ok') return 'ready';
  if (status === 'failed' || status === 'error') return 'danger';
  if (status === 'pending' || status === 'queued' || status === 'leased' || status === 'running') return 'warn';
  return 'neutral';
}

export default function RuntimeDiagnostics() {
  const state = getState();
  const egress = getRecentEgress(50);
  const auditSummary = getAuditSummary(12);
  const voiceCalls = getVoiceToolCalls(15);
  const dbStats = getDbStats();

  const recentRuns = (state.runs || []).slice(0, 10);
  const recentArtifacts = (state.artifacts || []).slice(0, 10);
  const pendingApprovals = state.pending_approvals || [];

  return (
    <AdminShell
      kicker="Runtime · madarX OS"
      title="Runtime diagnostics"
      description="Live SQLite-backed state — the same database powering every dashboard surface. Read-only, no client polling, no JSON dumps."
    >
      <div className="mkt-page" data-page="runtime">
        {/* ── Stats strip — mkt style, matches /projects + /marketplace ──── */}
        <section className="mkt-stats">
          <div className="mkt-stat">
            <b>{state.agents.length}</b>
            <span>Agents</span>
          </div>
          <div className="mkt-stat">
            <b>{state.schedules.length}</b>
            <span>Schedules</span>
          </div>
          <div className="mkt-stat">
            <b>{pendingApprovals.length}</b>
            <span>Approvals pending</span>
          </div>
          <div className="mkt-stat">
            <b>{formatBytes(dbStats.bytes)}</b>
            <span>DB size</span>
          </div>
          <div className="mkt-stat">
            <b>{(state.runs || []).length}</b>
            <span>Runs (recent)</span>
          </div>
          <div className="mkt-stat">
            <b>{(state.artifacts || []).length}</b>
            <span>Artifacts</span>
          </div>
        </section>

      {/* ── Pending approvals ───────────────────────────────────────────── */}
      <section className="admin-panel">
        <div className="admin-panel-head">
          <span>Pending approvals</span>
          <small>Tool calls awaiting owner confirmation. Approve or deny from the dashboard.</small>
        </div>
        {pendingApprovals.length === 0 ? (
          <EmptyState title="Nothing waiting">
            No approval requests are pending right now.
          </EmptyState>
        ) : (
          <div className="admin-card-list">
            {pendingApprovals.slice(0, 6).map((a) => (
              <div key={a.id} className="admin-record needs-action">
                <div className="admin-record-top">
                  <b>{a.summary || a.action_type}</b>
                  <StatusPill tone="warn">{a.action_type}</StatusPill>
                </div>
                <small>{a.created_at ? new Date(a.created_at).toLocaleString() : ''}</small>
              </div>
            ))}
          </div>
        )}
      </section>

      {/* ── Recent runs ─────────────────────────────────────────────────── */}
      <section className="admin-panel">
        <div className="admin-panel-head">
          <span>Recent runs</span>
          <small>Last {recentRuns.length} entries from the `runs` table.</small>
        </div>
        {recentRuns.length === 0 ? (
          <EmptyState title="No runs yet">Trigger an agent or use the main agent to generate activity.</EmptyState>
        ) : (
          <div className="admin-table-wrap">
            <table className="admin-table">
              <thead>
                <tr>
                  <th>Time</th>
                  <th>Title</th>
                  <th>Agent</th>
                  <th>Kind</th>
                  <th>Status</th>
                </tr>
              </thead>
              <tbody>
                {recentRuns.map((r) => (
                  <tr key={r.id}>
                    <td>{r.at ? new Date(r.at).toLocaleString() : ''}</td>
                    <td><b>{r.title || r.kind}</b>{r.preview ? <small>{String(r.preview).slice(0, 110)}</small> : null}</td>
                    <td>{r.agent || '—'}</td>
                    <td><code className="runtime-mono">{r.kind}</code></td>
                    <td><StatusPill tone={runStatusTone(r.status)}>{r.status || '—'}</StatusPill></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>

      {/* ── Recent artifacts ───────────────────────────────────────────── */}
      <section className="admin-panel">
        <div className="admin-panel-head">
          <span>Recent artifacts</span>
          <small>Stored documents from `artifacts`. Content + source_md fields are not shown here.</small>
        </div>
        {recentArtifacts.length === 0 ? (
          <EmptyState title="No artifacts yet">Ask the main agent to produce a brief or report.</EmptyState>
        ) : (
          <div className="admin-table-wrap">
            <table className="admin-table">
              <thead>
                <tr>
                  <th>Title</th>
                  <th>Kind</th>
                  <th>Agent</th>
                  <th>Project</th>
                  <th>Created</th>
                </tr>
              </thead>
              <tbody>
                {recentArtifacts.map((a) => (
                  <tr key={a.id}>
                    <td><b>{a.title || a.file_path}</b></td>
                    <td><StatusPill tone="neutral">{a.kind}</StatusPill></td>
                    <td>{a.agent_id || '—'}</td>
                    <td><code className="runtime-mono">{a.project_id || '—'}</code></td>
                    <td>{a.created_at ? new Date(a.created_at).toLocaleString() : ''}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>

      {/* ── Audit summary ───────────────────────────────────────────────── */}
      <section className="admin-panel">
        <div className="admin-panel-head">
          <span>Audit log — totals by type</span>
          <small>Top {auditSummary.length} categories. Full table is append-only and live in /admin.</small>
        </div>
        {auditSummary.length === 0 ? (
          <EmptyState title="No audit rows">Audit_logs is empty.</EmptyState>
        ) : (
          <div className="admin-table-wrap">
            <table className="admin-table">
              <thead>
                <tr>
                  <th>Type</th>
                  <th>Count</th>
                </tr>
              </thead>
              <tbody>
                {auditSummary.map((row) => (
                  <tr key={row.type}>
                    <td><code className="runtime-mono">{row.type}</code></td>
                    <td><b>{row.c.toLocaleString()}</b></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>

      {/* ── Voice tool calls ───────────────────────────────────────────── */}
      <section className="admin-panel">
        <div className="admin-panel-head">
          <span>Voice tool calls</span>
          <small>Last {voiceCalls.length} Realtime function-call dispatches recorded in `voice_tool_calls`.</small>
        </div>
        {voiceCalls.length === 0 ? (
          <EmptyState title="No voice calls yet">Open the Jarvis console and trigger a tool to see entries here.</EmptyState>
        ) : (
          <div className="admin-table-wrap">
            <table className="admin-table">
              <thead>
                <tr>
                  <th>Time</th>
                  <th>Tool</th>
                  <th>Status</th>
                  <th>Latency</th>
                  <th>Session</th>
                </tr>
              </thead>
              <tbody>
                {voiceCalls.map((row) => (
                  <tr key={row.id}>
                    <td>{row.created_at ? new Date(row.created_at).toLocaleTimeString() : ''}</td>
                    <td><code className="runtime-mono">{row.tool_name}</code></td>
                    <td><StatusPill tone={runStatusTone(row.status)}>{row.status || '—'}</StatusPill></td>
                    <td>{row.latency_ms != null ? `${row.latency_ms} ms` : '—'}</td>
                    <td><code className="runtime-mono" title={row.session_id || ''}>{row.session_id ? row.session_id.slice(0, 12) + '…' : '—'}</code></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>

      {/* ── Egress log ─────────────────────────────────────────────────── */}
      <section className="admin-panel">
        <div className="admin-panel-head">
          <span>Egress log</span>
          <small>Last {egress.length} external API calls recorded by tool adapters via wrapFetch.</small>
        </div>
        {egress.length === 0 ? (
          <EmptyState title="No egress yet">
            Make a web_fetch or supabase call to see records here.
          </EmptyState>
        ) : (
          <div className="admin-table-wrap">
            <table className="admin-table">
              <thead>
                <tr>
                  <th>Time</th>
                  <th>Tool</th>
                  <th>Host</th>
                  <th>Method</th>
                  <th>Status</th>
                  <th>In</th>
                  <th>Out</th>
                  <th>ms</th>
                </tr>
              </thead>
              <tbody>
                {egress.map((row) => (
                  <tr key={row.id}>
                    <td>{row.at ? new Date(row.at).toLocaleTimeString() : ''}</td>
                    <td><code className="runtime-mono">{row.tool_name}</code></td>
                    <td title={row.host}><code className="runtime-mono">{row.host}</code></td>
                    <td>{row.method}</td>
                    <td>
                      <StatusPill tone={statusTone(row.status_code, row.error)}>
                        {row.error ? 'ERR' : (row.status_code ?? '—')}
                      </StatusPill>
                    </td>
                    <td>{formatBytes(row.bytes_in)}</td>
                    <td>{formatBytes(row.bytes_out)}</td>
                    <td>{row.duration_ms != null ? row.duration_ms : '—'}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>
      </div>
    </AdminShell>
  );
}
