import { f as defineAdminEventHandler, h as requireAdminRole, cj as getCacheService, b as getDatabaseManager, ck as getSlowQueryThresholdMs, c5 as getJobQueue, bo as getStorageProvider, cl as isTracingEnabled } from '../../../../nitro/nitro.mjs';
import { getSearchService } from '../../../../_/index.mjs';
import { g as getDeliveryMetrics } from '../../../../_/delivery-metrics.mjs';
import 'node:crypto';
import 'jsonwebtoken';
import 'node:fs';
import 'node:module';
import 'node:path';
import 'node:url';
import 'node:http';
import 'node:https';
import 'node:events';
import 'node:buffer';
import 'pino';
import 'drizzle-orm/better-sqlite3';
import 'drizzle-orm/node-postgres';
import 'drizzle-orm/mysql2';
import 'better-sqlite3';
import 'pg';
import 'mysql2/promise';
import 'drizzle-orm';
import 'fs';
import 'path';
import 'prom-client';
import 'bcryptjs';
import '@node-rs/argon2';
import 'node:async_hooks';
import 'crypto';
import 'node:dns';
import 'node:util';
import 'node:net';
import 'fs/promises';
import 'url';
import 'semver';

var _a;
const VERSION = (_a = process.env.NOTTY_VERSION) != null ? _a : "0.16.0";
async function timeCheck(required, fn) {
  const start = process.hrtime.bigint();
  try {
    const result = await fn();
    return {
      status: result.status,
      required,
      durationMs: Math.round(Number(process.hrtime.bigint() - start) / 1e6),
      detail: result.detail
    };
  } catch (error) {
    return {
      status: "fail",
      required,
      durationMs: Math.round(Number(process.hrtime.bigint() - start) / 1e6),
      detail: error instanceof Error ? error.message : String(error)
    };
  }
}
function errorMessage(error) {
  return error instanceof Error ? error.message : String(error);
}
function calculateHitRate(hits, misses) {
  const total = hits + misses;
  return total > 0 ? hits / total : null;
}
function readTracingConfig() {
  var _a2, _b, _c;
  const enabled = isTracingEnabled();
  if (!enabled) {
    return {
      enabled: false,
      exporter: "disabled",
      endpoint: null,
      serviceName: null
    };
  }
  const baseEndpoint = (_a2 = process.env.OTEL_EXPORTER_OTLP_ENDPOINT) == null ? void 0 : _a2.replace(/\/+$/, "");
  const endpoint = (_b = process.env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT) != null ? _b : baseEndpoint ? `${baseEndpoint}/v1/traces` : "http://localhost:4318/v1/traces";
  return {
    enabled: true,
    exporter: "otlp-http",
    endpoint,
    serviceName: (_c = process.env.OTEL_SERVICE_NAME) != null ? _c : "@notty/server"
  };
}
async function readReadinessChecks() {
  const database = await timeCheck(true, async () => {
    var _a2, _b;
    const status = await getDatabaseManager().getStatus();
    if (!status.connected) {
      return { status: "fail", detail: (_a2 = status.error) != null ? _a2 : "not connected" };
    }
    return {
      status: "ok",
      detail: `${status.dialect} (${(_b = status.tablesCount) != null ? _b : 0} tables)`
    };
  });
  const storage = await timeCheck(false, () => {
    try {
      const provider = getStorageProvider();
      return Promise.resolve({ status: "ok", detail: provider.getType() });
    } catch (error) {
      return Promise.resolve({ status: "fail", detail: errorMessage(error) });
    }
  });
  const jobQueue = await timeCheck(false, () => {
    try {
      getJobQueue();
      return Promise.resolve({ status: "ok", detail: "running" });
    } catch (error) {
      return Promise.resolve({ status: "fail", detail: errorMessage(error) });
    }
  });
  const checks = { database, storage, jobQueue };
  const requiredFailed = Object.values(checks).some((c) => c.required && c.status !== "ok");
  return {
    status: requiredFailed ? "not_ready" : "ready",
    checks
  };
}
async function readCacheSnapshot() {
  var _a2, _b;
  try {
    const service = getCacheService();
    const adapter = service.getAdapter();
    const stats = await service.stats();
    return {
      adapter: {
        name: adapter.name,
        capabilities: { ...adapter.capabilities }
      },
      stats: {
        hits: stats.hits,
        misses: stats.misses,
        hitRate: calculateHitRate(stats.hits, stats.misses),
        entries: stats.entries,
        evictions: stats.evictions,
        evictionsByReason: { ...(_a2 = stats.evictionsByReason) != null ? _a2 : {} },
        bytes: (_b = stats.bytes) != null ? _b : null
      },
      error: null
    };
  } catch (error) {
    return {
      adapter: { name: "unknown", capabilities: {} },
      stats: {
        hits: 0,
        misses: 0,
        hitRate: null,
        entries: 0,
        evictions: 0,
        evictionsByReason: {},
        bytes: null
      },
      error: errorMessage(error)
    };
  }
}
async function readDatabaseSnapshot() {
  var _a2, _b, _c;
  const manager = getDatabaseManager();
  const status = await manager.getStatus();
  const replicas = manager.getReplicaInfo();
  const statementTimeoutMs = (_a2 = manager.getStatementTimeoutMs()) != null ? _a2 : null;
  return {
    dialect: status.dialect,
    connected: status.connected,
    tablesCount: (_b = status.tablesCount) != null ? _b : null,
    error: (_c = status.error) != null ? _c : null,
    replicas: {
      supported: replicas.dialect !== "sqlite",
      configured: replicas.configured,
      connected: replicas.connected
    },
    statementTimeoutMs,
    slowQueryThresholdMs: getSlowQueryThresholdMs()
  };
}
async function readSearchSnapshot() {
  var _a2;
  try {
    const service = getSearchService();
    const adapter = service.getAdapter();
    const health = await service.healthCheck();
    return {
      adapter: {
        name: adapter.name,
        capabilities: { ...adapter.capabilities }
      },
      health: { healthy: health.healthy, message: (_a2 = health.message) != null ? _a2 : null },
      error: null
    };
  } catch (error) {
    return {
      adapter: { name: "unknown", capabilities: {} },
      health: { healthy: false, message: errorMessage(error) },
      error: errorMessage(error)
    };
  }
}
function readRuntimeSnapshot() {
  const mem = process.memoryUsage();
  return {
    version: VERSION,
    environment: "production",
    nodeVersion: process.version,
    pid: process.pid,
    uptimeSeconds: process.uptime(),
    memory: {
      rss: mem.rss,
      heapUsed: mem.heapUsed,
      heapTotal: mem.heapTotal,
      external: mem.external
    }
  };
}
function readObservabilityConfig() {
  return {
    logger: "pino",
    metricsEndpoint: "/api/metrics",
    metricsPublic: process.env.METRICS_PUBLIC === "true",
    metricsTokenConfigured: Boolean(
      process.env.METRICS_TOKEN && process.env.METRICS_TOKEN.length > 0
    ),
    tracing: readTracingConfig()
  };
}
function readDeliveryMetricsSummary() {
  const metrics = getDeliveryMetrics();
  return {
    costThreshold: metrics.costThreshold,
    bufferLimit: metrics.bufferLimit,
    totals: { ...metrics.totals },
    startedAt: metrics.startedAt
  };
}
const overview_get = defineAdminEventHandler("admin:observability:overview", async (event) => {
  await requireAdminRole(event, ["super-admin", "admin"]);
  const [readiness, cache, database, search] = await Promise.all([
    readReadinessChecks(),
    readCacheSnapshot(),
    readDatabaseSnapshot(),
    readSearchSnapshot()
  ]);
  const data = {
    runtime: readRuntimeSnapshot(),
    observability: readObservabilityConfig(),
    readiness,
    cache,
    database,
    search,
    deliveryMetrics: readDeliveryMetricsSummary(),
    generatedAt: (/* @__PURE__ */ new Date()).toISOString()
  };
  return { success: true, data };
});

export { overview_get as default };
//# sourceMappingURL=overview.get.mjs.map
