// SPEC: PJ2026-01060508 Web哨兵 draft-2026-07-12-p17-monitor-central-persistence.
// Responsibility: Explicit one-shot SQLite snapshot import through the central Monitor PostgreSQL store.
import { readFileSync } from "node:fs";

import { createPostgresMonitorCentralStore, MONITOR_CENTRAL_SCHEMA_VERSION, structuredMonitorCentralError } from "./src/monitor-central-persistence";
import { importMonitorSqliteSnapshot, type MonitorSqliteSnapshot } from "./src/monitor-sqlite-migration";

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

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

let store: ReturnType<typeof createPostgresMonitorCentralStore> | null = null;
try {
  const snapshotPath = process.argv[2];
  if (!snapshotPath) throw Object.assign(new Error("snapshot path is required"), { code: "monitor_migration_snapshot_missing" });
  const snapshot = JSON.parse(readFileSync(snapshotPath, "utf8")) as MonitorSqliteSnapshot;
  store = createPostgresMonitorCentralStore(required("DATABASE_URL"), { poolMax: positive("MONITOR_CENTRAL_PG_POOL_MAX"), idleTimeoutSeconds: positive("MONITOR_CENTRAL_PG_IDLE_TIMEOUT_SECONDS") });
  await store.ping();
  if (await store.schemaVersion() !== MONITOR_CENTRAL_SCHEMA_VERSION) throw Object.assign(new Error("central monitor schema is not ready"), { code: "monitor_migration_schema_unready" });
  if (!(await store.capability()).ingest) throw Object.assign(new Error("central monitor ingest capability is unavailable"), { code: "monitor_migration_capability_unavailable" });
  console.log(JSON.stringify(await importMonitorSqliteSnapshot(snapshot, store)));
} catch (error) {
  console.log(JSON.stringify({ ok: false, error: structuredMonitorCentralError(error), valuesRedacted: true }));
  process.exitCode = 2;
} finally {
  await store?.close();
}
