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

const execFileP = promisify(execFile);

let _version = null;
async function coreVersion() {
  if (_version) return _version;
  try { _version = JSON.parse(await readFile(new URL('../../package.json', import.meta.url), 'utf8')).version || '0.0.0'; }
  catch { _version = '0.0.0'; }
  return _version;
}
let _hugo = null;
async function hugoVersion() {
  if (_hugo) return _hugo;
  try { const { stdout } = await execFileP('hugo', ['version']); _hugo = (stdout.match(/v[0-9][0-9.]*[^\s]*/) || ['?'])[0]; }
  catch { _hugo = '?'; }
  return _hugo;
}

// System-/Diagnose-Info fürs Admin-Panel. Reiner Builder (testbar); die Route hängt
// nur die zur Laufzeit ermittelten Versionen dran.
export function systemInfo({ version, hugo }) {
  return {
    core: { name: 'openbureau-core', version },
    site: config.site || null,
    auth: config.auth || 'supabase',
    admins: config.admins || [],
    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) => c.json(systemInfo({ version: await coreVersion(), hugo: await hugoVersion() })));

// Update-Check (token-frei): laufende Core-Version (Image, /app/package.json) vs. die
// im Repo VENDORTE Version (SITE_DIR/cms/core/api/package.json). Ist die vendorte neuer,
// wurde core aktualisiert aber noch nicht neu gebaut → "Rebuild nötig" (Update-Skript).
system.get('/update', async (c) => {
  const running = await coreVersion();
  const siteDir = process.env.SITE_DIR || '/site';
  const vendorPath = path.join(siteDir, process.env.CORE_VENDOR_PATH || 'cms/core', 'api/package.json');
  let vendored = null;
  try { vendored = JSON.parse(await readFile(vendorPath, 'utf8')).version || null; }
  catch { /* nicht als Subtree eingebunden → kein Vergleich möglich */ }
  return c.json({ running, vendored, available: !!(vendored && vendored !== running) });
});

export default system;
