/**
 * The child process launched by the dev supervisor.
 *
 *   bun run serve-entry.ts <appDir> <port> <mode> [hostname]
 *
 * It starts the dev server and prints the route table. Because it runs in its
 * own process, every restart re-imports all route modules fresh — that is how
 * the supervisor delivers live reload of edited server code.
 */

import { dirname } from "node:path";
import { startServer } from "./index.ts";
import { loadAppConfig, headToString, findStyleEntry, renderFontHead } from "@wrnexus/styles";
import type { Mode } from "@wrnexus/core";

const [appDir, portStr, modeStr, hostname] = process.argv.slice(2);

const mode = (modeStr as Mode) || "development";
const port = Number(portStr) || 3000;

// Load optional wrnexus.config.ts (sits next to the app/ dir) + resolve styles.
const appRoot = dirname(appDir!);
const config = await loadAppConfig(appRoot);
const styleEntry = findStyleEntry(appDir!, appRoot, config.styles?.entry);

const server = await startServer({
  appDir: appDir!,
  port,
  hostname,
  mode,
  styleEntry,
  stylesConfig: config.styles,
  head: [renderFontHead(config.fonts), headToString(config.head)].filter(Boolean).join("\n    "),
  seo: config.seo,
  security: config.security,
  theme: config.theme,
  i18n: config.i18n,
  db: config.db,
  databases: config.databases,
  realtime: config.realtime,
  storage: config.storage,
  mobile: config.mobile,
  pwa: config.pwa,
});
const r = server.router;

const group = (label: string, items: { raw: string }[]) => {
  if (!items.length) return;
  console.log(`  ${label}`);
  for (const it of items) console.log(`    ${it.raw}`);
};

console.log(`\n  ⚡ WrNexus — ${server.url}\n`);
group("Pages", r.pages);
group("API", r.api);
group("Realtime", r.realtime);
if (r.components.length) {
  console.log("  Components");
  for (const c of r.components) console.log(`    ${c.name}`);
}
console.log("");
