import { existsSync, mkdirSync, statSync, copyFileSync, readdirSync, unlinkSync } from 'node:fs';
import Database from 'better-sqlite3';
import { j as join, d as dirname, b as basename } from '../shared/ccjk.bQ7Dh1g4.mjs';

const CURRENT_SCHEMA_VERSION = 1;
class DatabaseHealthMonitor {
  db;
  dbPath;
  backupDir;
  constructor(dbPath) {
    this.dbPath = dbPath;
    this.backupDir = join(dirname(dbPath), "backups");
    if (!existsSync(this.backupDir)) {
      mkdirSync(this.backupDir, { recursive: true });
    }
    this.db = new Database(dbPath, { readonly: false });
  }
  /**
   * Run comprehensive health check
   */
  async runHealthCheck() {
    const errors = [];
    const recommendations = [];
    try {
      const integrity = await this.checkIntegrity();
      const wal = await this.checkWAL();
      const size = await this.checkSize();
      const performance = await this.checkPerformance();
      recommendations.push(...wal.recommendations);
      recommendations.push(...size.recommendations);
      recommendations.push(...performance.recommendations);
      let status = "healthy" /* HEALTHY */;
      if (!integrity.passed) {
        status = "critical" /* CRITICAL */;
        errors.push("Database integrity check failed");
      } else if (size.utilizationPercent < 50) {
        status = "warning" /* WARNING */;
        recommendations.push("Consider running VACUUM to reclaim space");
      } else if (wal.walSize > 10 * 1024 * 1024) {
        status = "warning" /* WARNING */;
        recommendations.push("WAL file is large, consider checkpointing");
      } else if (performance.queryTime > 100) {
        status = "warning" /* WARNING */;
        recommendations.push("Query performance is degraded");
      }
      return {
        status,
        timestamp: Date.now(),
        checks: {
          integrity,
          wal,
          size,
          performance
        },
        recommendations: [...new Set(recommendations)],
        // Remove duplicates
        errors
      };
    } catch (error) {
      return {
        status: "unknown" /* UNKNOWN */,
        timestamp: Date.now(),
        checks: {
          integrity: { passed: false, errors: [String(error)], corruptedTables: [], duration: 0 },
          wal: { mode: "unknown", walSize: 0, shmSize: 0, checkpointable: false, recommendations: [] },
          size: { dbSize: 0, walSize: 0, totalSize: 0, pageCount: 0, pageSize: 0, freePages: 0, utilizationPercent: 0, recommendations: [] },
          performance: { queryTime: 0, writeTime: 0, indexEfficiency: 0, cacheHitRate: 0, recommendations: [] }
        },
        recommendations: [],
        errors: [`Health check failed: ${error instanceof Error ? error.message : String(error)}`]
      };
    }
  }
  /**
   * Check database integrity
   */
  async checkIntegrity() {
    const _startTime = Date.now();
    const errors = [];
    const corruptedTables = [];
    try {
      const result = this.db.prepare("PRAGMA integrity_check").all();
      const passed = result.length === 1 && result[0].integrity_check === "ok";
      if (!passed) {
        for (const row of result) {
          const msg = row.integrity_check;
          errors.push(msg);
          const tableMatch = msg.match(/table (\w+)/);
          if (tableMatch) {
            corruptedTables.push(tableMatch[1]);
          }
        }
      }
      const fkResult = this.db.prepare("PRAGMA foreign_key_check").all();
      if (fkResult.length > 0) {
        errors.push(`Foreign key violations found: ${fkResult.length}`);
      }
      return {
        passed: passed && fkResult.length === 0,
        errors,
        corruptedTables: [...new Set(corruptedTables)],
        duration: Date.now() - _startTime
      };
    } catch (error) {
      return {
        passed: false,
        errors: [`Integrity check failed: ${error instanceof Error ? error.message : String(error)}`],
        corruptedTables: [],
        duration: Date.now() - _startTime
      };
    }
  }
  /**
   * Check WAL status and recommend checkpoint if needed
   */
  async checkWAL() {
    const recommendations = [];
    try {
      const modeResult = this.db.prepare("PRAGMA journal_mode").get();
      const mode = modeResult.journal_mode;
      const walPath = `${this.dbPath}-wal`;
      const shmPath = `${this.dbPath}-shm`;
      const walSize = existsSync(walPath) ? statSync(walPath).size : 0;
      const shmSize = existsSync(shmPath) ? statSync(shmPath).size : 0;
      const checkpointable = walSize > 1024 * 1024;
      if (checkpointable) {
        recommendations.push("WAL file is large, run checkpoint to merge changes");
      }
      if (walSize > 10 * 1024 * 1024) {
        recommendations.push("WAL file exceeds 10MB, immediate checkpoint recommended");
      }
      return {
        mode,
        walSize,
        shmSize,
        checkpointable,
        recommendations
      };
    } catch (error) {
      return {
        mode: "unknown",
        walSize: 0,
        shmSize: 0,
        checkpointable: false,
        recommendations: [`WAL check failed: ${error instanceof Error ? error.message : String(error)}`]
      };
    }
  }
  /**
   * Checkpoint WAL to main database
   */
  async checkpoint(mode = "RESTART") {
    try {
      const result = this.db.prepare(`PRAGMA wal_checkpoint(${mode})`).get();
      return {
        success: result.busy === 0,
        walFrames: result.log,
        checkpointed: result.checkpointed
      };
    } catch (error) {
      return {
        success: false,
        walFrames: 0,
        checkpointed: 0,
        error: error instanceof Error ? error.message : String(error)
      };
    }
  }
  /**
   * Check database size and utilization
   */
  async checkSize() {
    const recommendations = [];
    try {
      const dbSize = existsSync(this.dbPath) ? statSync(this.dbPath).size : 0;
      const walPath = `${this.dbPath}-wal`;
      const walSize = existsSync(walPath) ? statSync(walPath).size : 0;
      const pageCountResult = this.db.prepare("PRAGMA page_count").get();
      const pageSizeResult = this.db.prepare("PRAGMA page_size").get();
      const freePagesResult = this.db.prepare("PRAGMA freelist_count").get();
      const pageCount = pageCountResult.page_count;
      const pageSize = pageSizeResult.page_size;
      const freePages = freePagesResult.freelist_count;
      const utilizationPercent = pageCount > 0 ? (pageCount - freePages) / pageCount * 100 : 100;
      if (utilizationPercent < 70) {
        recommendations.push(`Database utilization is ${utilizationPercent.toFixed(1)}%, consider VACUUM`);
      }
      if (freePages > pageCount * 0.3) {
        recommendations.push(`${freePages} free pages detected, VACUUM recommended`);
      }
      if (dbSize > 100 * 1024 * 1024) {
        recommendations.push("Database exceeds 100MB, consider archiving old data");
      }
      return {
        dbSize,
        walSize,
        totalSize: dbSize + walSize,
        pageCount,
        pageSize,
        freePages,
        utilizationPercent,
        recommendations
      };
    } catch (error) {
      return {
        dbSize: 0,
        walSize: 0,
        totalSize: 0,
        pageCount: 0,
        pageSize: 0,
        freePages: 0,
        utilizationPercent: 0,
        recommendations: [`Size check failed: ${error instanceof Error ? error.message : String(error)}`]
      };
    }
  }
  /**
   * Check database performance
   */
  async checkPerformance() {
    const recommendations = [];
    try {
      const queryStart = Date.now();
      this.db.prepare("SELECT COUNT(*) FROM contexts").get();
      const queryTime = Date.now() - queryStart;
      const writeStart = Date.now();
      this.db.prepare("BEGIN").run();
      this.db.prepare("ROLLBACK").run();
      const writeTime = Date.now() - writeStart;
      const indexes = this.db.prepare(`
        SELECT name FROM sqlite_master WHERE type = 'index' AND sql IS NOT NULL
      `).all();
      const indexEfficiency = indexes.length > 0 ? 100 : 0;
      const cacheHitRate = 95;
      if (queryTime > 50) {
        recommendations.push("Query performance is slow, check indexes");
      }
      if (writeTime > 20) {
        recommendations.push("Write performance is slow, consider optimizing");
      }
      if (indexes.length < 4) {
        recommendations.push("Few indexes detected, query performance may be suboptimal");
      }
      return {
        queryTime,
        writeTime,
        indexEfficiency,
        cacheHitRate,
        recommendations
      };
    } catch (error) {
      return {
        queryTime: 0,
        writeTime: 0,
        indexEfficiency: 0,
        cacheHitRate: 0,
        recommendations: [`Performance check failed: ${error instanceof Error ? error.message : String(error)}`]
      };
    }
  }
  /**
   * Create database backup
   */
  async backup(label) {
    const _startTime = Date.now();
    try {
      await this.checkpoint("FULL");
      const timestamp = Date.now();
      const dateStr = new Date(timestamp).toISOString().replace(/[:.]/g, "-");
      const labelStr = label ? `-${label}` : "";
      const backupFilename = `contexts-${dateStr}${labelStr}.db`;
      const backupPath = join(this.backupDir, backupFilename);
      copyFileSync(this.dbPath, backupPath);
      const stats = this.db.prepare("SELECT COUNT(*) as count FROM contexts").get();
      const projectStats = this.db.prepare("SELECT COUNT(*) as count FROM projects").get();
      const dbSize = statSync(backupPath).size;
      const metadata = {
        timestamp,
        dbSize,
        contextCount: stats.count,
        projectCount: projectStats.count,
        version: String(CURRENT_SCHEMA_VERSION)
      };
      const metadataPath = `${backupPath}.meta.json`;
      const fs = require("node:fs");
      fs.writeFileSync(metadataPath, JSON.stringify(metadata, null, 2));
      await this.cleanupOldBackups(10);
      return {
        success: true,
        backupPath,
        metadata,
        duration: Date.now() - _startTime
      };
    } catch (error) {
      return {
        success: false,
        backupPath: "",
        metadata: {
          timestamp: Date.now(),
          dbSize: 0,
          contextCount: 0,
          projectCount: 0,
          version: String(CURRENT_SCHEMA_VERSION)
        },
        duration: Date.now() - _startTime,
        error: error instanceof Error ? error.message : String(error)
      };
    }
  }
  /**
   * Restore database from backup
   */
  async restore(backupPath) {
    const _startTime = Date.now();
    try {
      if (!existsSync(backupPath)) {
        throw new Error(`Backup file not found: ${backupPath}`);
      }
      const metadataPath = `${backupPath}.meta.json`;
      let metadata;
      if (existsSync(metadataPath)) {
        const fs = require("node:fs");
        metadata = JSON.parse(fs.readFileSync(metadataPath, "utf-8"));
      } else {
        metadata = {
          timestamp: statSync(backupPath).mtimeMs,
          dbSize: statSync(backupPath).size,
          contextCount: 0,
          projectCount: 0,
          version: String(CURRENT_SCHEMA_VERSION)
        };
      }
      this.db.close();
      const currentBackupPath = `${this.dbPath}.pre-restore-${Date.now()}.bak`;
      if (existsSync(this.dbPath)) {
        copyFileSync(this.dbPath, currentBackupPath);
      }
      copyFileSync(backupPath, this.dbPath);
      this.db = new Database(this.dbPath);
      const integrity = await this.checkIntegrity();
      if (!integrity.passed) {
        copyFileSync(currentBackupPath, this.dbPath);
        this.db = new Database(this.dbPath);
        throw new Error("Restored database failed integrity check");
      }
      return {
        success: true,
        restoredFrom: backupPath,
        metadata,
        duration: Date.now() - _startTime
      };
    } catch (error) {
      return {
        success: false,
        restoredFrom: backupPath,
        metadata: {
          timestamp: 0,
          dbSize: 0,
          contextCount: 0,
          projectCount: 0,
          version: String(CURRENT_SCHEMA_VERSION)
        },
        duration: Date.now() - _startTime,
        error: error instanceof Error ? error.message : String(error)
      };
    }
  }
  /**
   * List available backups
   */
  listBackups() {
    const backups = [];
    if (!existsSync(this.backupDir)) {
      return backups;
    }
    const files = readdirSync(this.backupDir);
    for (const file of files) {
      if (file.endsWith(".db") && !file.endsWith(".bak")) {
        const backupPath = join(this.backupDir, file);
        const metadataPath = `${backupPath}.meta.json`;
        let metadata;
        if (existsSync(metadataPath)) {
          const fs = require("node:fs");
          metadata = JSON.parse(fs.readFileSync(metadataPath, "utf-8"));
        } else {
          metadata = {
            timestamp: statSync(backupPath).mtimeMs,
            dbSize: statSync(backupPath).size,
            contextCount: 0,
            projectCount: 0,
            version: String(CURRENT_SCHEMA_VERSION)
          };
        }
        backups.push({ path: backupPath, metadata });
      }
    }
    return backups.sort((a, b) => b.metadata.timestamp - a.metadata.timestamp);
  }
  /**
   * Clean up old backups
   */
  async cleanupOldBackups(keepCount) {
    const backups = this.listBackups();
    if (backups.length <= keepCount) {
      return 0;
    }
    const toDelete = backups.slice(keepCount);
    let deleted = 0;
    for (const backup of toDelete) {
      try {
        unlinkSync(backup.path);
        const metadataPath = `${backup.path}.meta.json`;
        if (existsSync(metadataPath)) {
          unlinkSync(metadataPath);
        }
        deleted++;
      } catch {
      }
    }
    return deleted;
  }
  /**
   * Attempt automatic recovery
   */
  async attemptRecovery() {
    const actions = [];
    const errors = [];
    try {
      const integrity = await this.checkIntegrity();
      if (!integrity.passed) {
        const backups = this.listBackups();
        if (backups.length > 0) {
          actions.push("Database corruption detected, attempting restore from backup");
          const restoreResult = await this.restore(backups[0].path);
          if (restoreResult.success) {
            actions.push(`Successfully restored from backup: ${basename(backups[0].path)}`);
            return { success: true, actions, errors };
          } else {
            errors.push(`Restore failed: ${restoreResult.error}`);
          }
        } else {
          errors.push("No backups available for recovery");
        }
        return { success: false, actions, errors };
      }
      const wal = await this.checkWAL();
      if (wal.checkpointable) {
        actions.push("Checkpointing WAL");
        const checkpointResult = await this.checkpoint("RESTART");
        if (checkpointResult.success) {
          actions.push(`Checkpointed ${checkpointResult.checkpointed} frames`);
        } else {
          errors.push(`Checkpoint failed: ${checkpointResult.error}`);
        }
      }
      const size = await this.checkSize();
      if (size.utilizationPercent < 70) {
        actions.push("Running VACUUM to reclaim space");
        try {
          this.db.prepare("VACUUM").run();
          actions.push("VACUUM completed successfully");
        } catch (error) {
          errors.push(`VACUUM failed: ${error instanceof Error ? error.message : String(error)}`);
        }
      }
      return {
        success: errors.length === 0,
        actions,
        errors
      };
    } catch (error) {
      errors.push(`Recovery failed: ${error instanceof Error ? error.message : String(error)}`);
      return { success: false, actions, errors };
    }
  }
  /**
   * Get schema version
   */
  getSchemaVersion() {
    try {
      const result = this.db.prepare("PRAGMA user_version").get();
      return result.user_version;
    } catch {
      return 0;
    }
  }
  /**
   * Set schema version
   */
  setSchemaVersion(version) {
    this.db.prepare(`PRAGMA user_version = ${version}`).run();
  }
  /**
   * Apply migrations
   */
  async applyMigrations(migrations) {
    const applied = [];
    const errors = [];
    const currentVersion = this.getSchemaVersion();
    const sortedMigrations = migrations.sort((a, b) => a.version - b.version);
    for (const migration of sortedMigrations) {
      if (migration.version <= currentVersion) {
        continue;
      }
      try {
        await this.backup(`pre-migration-v${migration.version}`);
        this.db.prepare("BEGIN").run();
        migration.up(this.db);
        this.setSchemaVersion(migration.version);
        this.db.prepare("COMMIT").run();
        applied.push(migration.version);
      } catch (error) {
        this.db.prepare("ROLLBACK").run();
        errors.push(`Migration v${migration.version} failed: ${error instanceof Error ? error.message : String(error)}`);
        break;
      }
    }
    return {
      success: errors.length === 0,
      applied,
      errors
    };
  }
  /**
   * Close database connection
   */
  close() {
    this.db.close();
  }
}

const DEFAULT_CONFIG = {
  silent: false,
  walThresholdMB: 10,
  diskUtilizationThreshold: 70,
  backupAgeThresholdDays: 7,
  enableHistory: true
};
class HealthAlertsManager {
  monitor;
  config;
  historyPath;
  dbPath;
  constructor(dbPath, config) {
    this.dbPath = dbPath;
    this.monitor = new DatabaseHealthMonitor(dbPath);
    this.config = { ...DEFAULT_CONFIG, ...config };
    this.historyPath = join(dirname(dbPath), "alert-history.json");
  }
  /**
   * Run health checks and generate alerts
   */
  async checkHealth() {
    const alerts = [];
    try {
      const health = await this.monitor.runHealthCheck();
      if (!health.checks.integrity.passed) {
        alerts.push({
          severity: "critical" /* CRITICAL */,
          category: "corruption",
          message: "Database corruption detected",
          action: "Run: ccjk context recover",
          timestamp: Date.now()
        });
        for (const error of health.checks.integrity.errors) {
          alerts.push({
            severity: "critical" /* CRITICAL */,
            category: "corruption",
            message: error,
            timestamp: Date.now()
          });
        }
      }
      const walSizeMB = health.checks.wal.walSize / (1024 * 1024);
      if (walSizeMB > this.config.walThresholdMB) {
        alerts.push({
          severity: "warning" /* WARNING */,
          category: "wal",
          message: `WAL file is ${walSizeMB.toFixed(1)}MB (threshold: ${this.config.walThresholdMB}MB)`,
          action: "Run: ccjk context checkpoint",
          timestamp: Date.now()
        });
      } else if (walSizeMB > this.config.walThresholdMB / 2) {
        alerts.push({
          severity: "info" /* INFO */,
          category: "wal",
          message: `WAL file is ${walSizeMB.toFixed(1)}MB`,
          action: "Consider checkpointing soon",
          timestamp: Date.now()
        });
      }
      if (health.checks.size.utilizationPercent < this.config.diskUtilizationThreshold) {
        alerts.push({
          severity: "warning" /* WARNING */,
          category: "disk",
          message: `Disk utilization is ${health.checks.size.utilizationPercent.toFixed(1)}% (threshold: ${this.config.diskUtilizationThreshold}%)`,
          action: "Run: ccjk context vacuum",
          timestamp: Date.now()
        });
      }
      const backupAlert = await this.checkBackupStatus();
      if (backupAlert) {
        alerts.push(backupAlert);
      }
      if (health.checks.performance.queryTime > 100) {
        alerts.push({
          severity: "warning" /* WARNING */,
          category: "performance",
          message: `Query performance is slow (${health.checks.performance.queryTime}ms)`,
          action: "Check database indexes",
          timestamp: Date.now()
        });
      }
      if (this.config.enableHistory && alerts.length > 0) {
        await this.logToHistory(alerts, health.status);
      }
      return alerts;
    } catch (error) {
      return [{
        severity: "critical" /* CRITICAL */,
        category: "corruption",
        message: `Health check failed: ${error instanceof Error ? error.message : String(error)}`,
        timestamp: Date.now()
      }];
    }
  }
  /**
   * Check backup status
   */
  async checkBackupStatus() {
    try {
      const backups = this.monitor.listBackups();
      if (backups.length === 0) {
        return {
          severity: "warning" /* WARNING */,
          category: "backup",
          message: "No backups found",
          action: "Run: ccjk context backup",
          timestamp: Date.now()
        };
      }
      const latestBackup = backups[0];
      const ageMs = Date.now() - latestBackup.metadata.timestamp;
      const ageDays = ageMs / (1e3 * 60 * 60 * 24);
      if (ageDays > this.config.backupAgeThresholdDays) {
        return {
          severity: "warning" /* WARNING */,
          category: "backup",
          message: `Latest backup is ${Math.floor(ageDays)} days old (threshold: ${this.config.backupAgeThresholdDays} days)`,
          action: "Run: ccjk context backup",
          timestamp: Date.now()
        };
      }
      if (ageDays > this.config.backupAgeThresholdDays / 2) {
        return {
          severity: "info" /* INFO */,
          category: "backup",
          message: `Latest backup is ${Math.floor(ageDays)} days old`,
          action: "Consider creating a new backup",
          timestamp: Date.now()
        };
      }
      return null;
    } catch {
      return null;
    }
  }
  /**
   * Display alerts with emoji indicators
   */
  displayAlerts(alerts) {
    if (alerts.length === 0) {
      return;
    }
    console.log("\n\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501");
    console.log("\u{1F4CA} Database Health Alerts");
    console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\n");
    const critical = alerts.filter((a) => a.severity === "critical" /* CRITICAL */);
    const warnings = alerts.filter((a) => a.severity === "warning" /* WARNING */);
    const info = alerts.filter((a) => a.severity === "info" /* INFO */);
    if (critical.length > 0) {
      for (const alert of critical) {
        console.log(`\u{1F534} CRITICAL: ${alert.message}`);
        if (alert.action) {
          console.log(`   \u2192 ${alert.action}`);
        }
      }
      console.log();
    }
    if (warnings.length > 0) {
      for (const alert of warnings) {
        console.log(`\u{1F7E1} WARNING: ${alert.message}`);
        if (alert.action) {
          console.log(`   \u2192 ${alert.action}`);
        }
      }
      console.log();
    }
    if (info.length > 0) {
      for (const alert of info) {
        console.log(`\u{1F4A1} INFO: ${alert.message}`);
        if (alert.action) {
          console.log(`   \u2192 ${alert.action}`);
        }
      }
      console.log();
    }
    console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\n");
  }
  /**
   * Log alerts to history
   */
  async logToHistory(alerts, healthStatus) {
    try {
      const fs = await import('node:fs/promises');
      let history = [];
      if (existsSync(this.historyPath)) {
        const content = await fs.readFile(this.historyPath, "utf-8");
        history = JSON.parse(content);
      }
      history.unshift({
        timestamp: Date.now(),
        alerts,
        healthStatus,
        resolved: false
      });
      history = history.slice(0, 100);
      await fs.writeFile(this.historyPath, JSON.stringify(history, null, 2));
    } catch {
    }
  }
  /**
   * Get alert history
   */
  async getHistory(limit = 10) {
    try {
      if (!existsSync(this.historyPath)) {
        return [];
      }
      const fs = await import('node:fs/promises');
      const content = await fs.readFile(this.historyPath, "utf-8");
      const history = JSON.parse(content);
      return history.slice(0, limit);
    } catch {
      return [];
    }
  }
  /**
   * Mark alerts as resolved
   */
  async markResolved(timestamp) {
    try {
      if (!existsSync(this.historyPath)) {
        return;
      }
      const fs = await import('node:fs/promises');
      const content = await fs.readFile(this.historyPath, "utf-8");
      const history = JSON.parse(content);
      const entry = history.find((e) => e.timestamp === timestamp);
      if (entry) {
        entry.resolved = true;
        await fs.writeFile(this.historyPath, JSON.stringify(history, null, 2));
      }
    } catch {
    }
  }
  /**
   * Clear alert history
   */
  async clearHistory() {
    try {
      if (existsSync(this.historyPath)) {
        const fs = await import('node:fs/promises');
        await fs.unlink(this.historyPath);
      }
    } catch {
    }
  }
  /**
   * Get summary statistics
   */
  async getSummary() {
    const history = await this.getHistory(100);
    if (history.length === 0) {
      return {
        totalAlerts: 0,
        criticalCount: 0,
        warningCount: 0,
        infoCount: 0,
        unresolvedCount: 0
      };
    }
    const unresolved = history.filter((e) => !e.resolved);
    const allAlerts = unresolved.flatMap((e) => e.alerts);
    return {
      totalAlerts: allAlerts.length,
      criticalCount: allAlerts.filter((a) => a.severity === "critical" /* CRITICAL */).length,
      warningCount: allAlerts.filter((a) => a.severity === "warning" /* WARNING */).length,
      infoCount: allAlerts.filter((a) => a.severity === "info" /* INFO */).length,
      unresolvedCount: unresolved.length,
      lastCheckTime: history[0]?.timestamp
    };
  }
  /**
   * Close monitor
   */
  close() {
    this.monitor.close();
  }
}
async function runStartupHealthCheck(dbPath, config) {
  if (!existsSync(dbPath)) {
    return [];
  }
  if (config?.silent) {
    return [];
  }
  const manager = new HealthAlertsManager(dbPath, config);
  try {
    const alerts = await manager.checkHealth();
    if (alerts.length > 0) {
      manager.displayAlerts(alerts);
    }
    return alerts;
  } finally {
    manager.close();
  }
}

export { HealthAlertsManager, runStartupHealthCheck };
