import { Hono } from 'hono';
import { readFile } from 'node:fs/promises';
import { config } from '../config.js';
import { manager } from '../plugins.js';
import { requireAdmin } from '../auth.js';

// System-/Diagnose-Info für das Admin-Panel: welche core-Version läuft, welche
// Plugins aktiv sind, welches Content-Modell die Site fährt. Rein lesend, Admin.
// Reine Builder-Funktion (testbar) — die Route hängt nur Version + Hugo dran.
export function systemInfo({ version, hugo }) {
  return {
    core: { name: 'openbureau-core', version },
    site: config.site || null,
    auth: config.auth || 'supabase',
    plugins: manager.plugins.map((p) => ({
      name: p.name,
      routes: (p.routes || []).length,
      migrations: (p.migrations || []).length,
    })),
    collections: config.collections.map((c) => ({
      kind: c.kind, label: c.label, statKey: c.statKey || null, fields: (c.fields || []).length,
    })),
    hugo,
  };
}

const system = new Hono();
system.use('*', requireAdmin);
system.get('/', async (c) => {
  let version = '0.0.0';
  try {
    const pkg = JSON.parse(await readFile(new URL('../../package.json', import.meta.url), 'utf8'));
    version = pkg.version || version;
  } catch { /* package.json nicht lesbar → 0.0.0 */ }
  return c.json(systemInfo({ version, hugo: '0.161.1+extended' }));
});

export default system;
