// SPEC: PJ2026-01060508 Web哨兵 draft-2026-07-12-p17-monitor-central-persistence.
// Responsibility: Environment-projected bootstrap for the independent central Monitor HTTP service.
import { createMonitorCentralService, createPostgresMonitorCentralStore, structuredMonitorCentralError } from "./src/monitor-central-persistence";

function requiredString(name: string): string {
  const value = process.env[name];
  if (!value) throw Object.assign(new Error(`${name} is required`), { code: "monitor_central_runtime_config_missing" });
  return value;
}

function requiredPositiveInteger(name: string): number {
  const value = Number(requiredString(name));
  if (!Number.isSafeInteger(value) || value < 1) throw Object.assign(new Error(`${name} must be a positive integer`), { code: "monitor_central_runtime_config_invalid" });
  return value;
}

try {
  const databaseUrl = requiredString("DATABASE_URL");
  const store = createPostgresMonitorCentralStore(databaseUrl, { poolMax: requiredPositiveInteger("MONITOR_CENTRAL_PG_POOL_MAX"), idleTimeoutSeconds: requiredPositiveInteger("MONITOR_CENTRAL_PG_IDLE_TIMEOUT_SECONDS") });
  await store.migrate();
  const service = createMonitorCentralService({ store, pageSize: requiredPositiveInteger("MONITOR_CENTRAL_PAGE_SIZE") });
  const server = Bun.serve({ hostname: requiredString("MONITOR_CENTRAL_HOST"), port: requiredPositiveInteger("MONITOR_CENTRAL_PORT"), fetch: service.fetch });
  console.log(JSON.stringify({ ok: true, service: "monitor-central", port: server.port, valuesRedacted: true }));
} catch (error) {
  const structured = { ok: false, error: structuredMonitorCentralError(error), valuesRedacted: true };
  console.log(JSON.stringify(structured));
  process.exitCode = 2;
}
