import { fileURLToPath as __fileURLToPath } from 'url';
import { dirname as __pathDirname } from 'path';
const __filename = __fileURLToPath(import.meta.url);
const __dirname = __pathDirname(__filename);
import { Command } from "commander";
import chalk from "chalk";
import ora from "ora";
import { SessionMonitor } from "../../core/monitoring/session-monitor.js";
import { FrameManager } from "../../core/context/index.js";
import Database from "better-sqlite3";
import * as fs from "fs/promises";
import * as path from "path";
import { spawn } from "child_process";
function createMonitorCommand() {
  const cmd = new Command("monitor").description("Run background monitoring for automatic triggers").option("--start", "Start monitoring daemon").option("--stop", "Stop monitoring daemon").option("--status", "Check monitor status").option("--config", "Show monitor configuration").option("--activity", "Update activity timestamp").option("--daemon", "Run as daemon (background process)").option("--foreground", "Run in foreground (for testing)").option("--interval <seconds>", "Check interval in seconds", "30").option("--idle <minutes>", "Idle timeout in minutes", "5").action(async (options) => {
    const spinner = ora();
    try {
      const projectRoot = await getProjectRoot();
      const dbPath = path.join(
        projectRoot,
        ".stackmemory",
        "db",
        "stackmemory.db"
      );
      try {
        await fs.access(dbPath);
      } catch {
        console.error(chalk.red("\u2717 StackMemory not initialized"));
        console.log(chalk.yellow("Run: stackmemory init"));
        process.exit(1);
      }
      if (options.start) {
        await startMonitor(projectRoot, options, spinner);
      } else if (options.stop) {
        await stopMonitor(projectRoot, spinner);
      } else if (options.status) {
        await showStatus(projectRoot);
      } else if (options.config) {
        await showConfig(projectRoot);
      } else if (options.activity) {
        await updateActivity(projectRoot);
      } else if (options.daemon) {
        await runDaemon(projectRoot, options);
      } else if (options.foreground) {
        await runForeground(projectRoot, options);
      } else {
        await showStatus(projectRoot);
      }
    } catch (error) {
      spinner.fail(chalk.red(`Error: ${error}`));
      process.exit(1);
    }
  });
  return cmd;
}
async function startMonitor(projectRoot, options, spinner) {
  spinner.start("Starting monitor daemon...");
  const pidFile = path.join(projectRoot, ".stackmemory", "monitor.pid");
  try {
    const pid = await fs.readFile(pidFile, "utf-8");
    try {
      process.kill(parseInt(pid), 0);
      spinner.fail(chalk.yellow("Monitor already running"));
      console.log(chalk.gray(`PID: ${pid}`));
      return;
    } catch {
      await fs.unlink(pidFile).catch(() => {
      });
    }
  } catch {
  }
  const daemon = spawn(
    process.execPath,
    [
      process.argv[1],
      "monitor",
      "--daemon",
      "--interval",
      options.interval || "30",
      "--idle",
      options.idle || "5"
    ],
    {
      cwd: projectRoot,
      detached: true,
      stdio: ["ignore", "ignore", "ignore"]
    }
  );
  await fs.writeFile(pidFile, daemon.pid.toString(), "utf-8");
  daemon.unref();
  spinner.succeed(chalk.green("\u2705 Monitor daemon started"));
  console.log(chalk.gray(`PID: ${daemon.pid}`));
  console.log(chalk.gray(`Check interval: ${options.interval || 30}s`));
  console.log(chalk.gray(`Idle timeout: ${options.idle || 5}min`));
  console.log(chalk.bold("\n\u{1F50D} Monitoring:"));
  console.log("  \u2022 Context usage (warns at 60%, saves at 85%)");
  console.log("  \u2022 Idle detection (handoff after 5min)");
  console.log("  \u2022 Session end (auto-save on exit)");
  console.log(chalk.gray("\nStop with: stackmemory monitor --stop"));
}
async function stopMonitor(projectRoot, spinner) {
  spinner.start("Stopping monitor daemon...");
  const pidFile = path.join(projectRoot, ".stackmemory", "monitor.pid");
  try {
    const pid = parseInt(await fs.readFile(pidFile, "utf-8"));
    process.kill(pid, "SIGTERM");
    await fs.unlink(pidFile);
    spinner.succeed(chalk.green("\u2705 Monitor daemon stopped"));
  } catch (error) {
    spinner.fail(chalk.yellow("Monitor not running"));
  }
}
async function showStatus(projectRoot) {
  const pidFile = path.join(projectRoot, ".stackmemory", "monitor.pid");
  const statusFile = path.join(projectRoot, ".stackmemory", "monitor.status");
  console.log(chalk.bold("\n\u{1F4CA} Monitor Status\n"));
  let isRunning = false;
  let pid;
  try {
    pid = parseInt(await fs.readFile(pidFile, "utf-8"));
    process.kill(pid, 0);
    isRunning = true;
  } catch {
  }
  if (isRunning && pid) {
    console.log(chalk.green("\u2705 Monitor is running"));
    console.log(chalk.gray(`PID: ${pid}`));
    try {
      const status = JSON.parse(await fs.readFile(statusFile, "utf-8"));
      console.log(chalk.bold("\nLast Check:"));
      console.log(`  Time: ${new Date(status.lastCheck).toLocaleString()}`);
      console.log(`  Context: ${Math.round(status.contextPercentage * 100)}%`);
      console.log(
        `  Status: ${getStatusEmoji(status.contextStatus)} ${status.contextStatus}`
      );
      if (status.lastActivity) {
        const idleMinutes = Math.round(
          (Date.now() - new Date(status.lastActivity).getTime()) / 6e4
        );
        console.log(`  Idle: ${idleMinutes} minutes`);
      }
      if (status.lastLedgerSave) {
        console.log(chalk.bold("\nLast Ledger Save:"));
        console.log(`  ${new Date(status.lastLedgerSave).toLocaleString()}`);
      }
      if (status.lastHandoff) {
        console.log(chalk.bold("\nLast Handoff:"));
        console.log(`  ${new Date(status.lastHandoff).toLocaleString()}`);
      }
    } catch {
    }
  } else {
    console.log(chalk.yellow("\u26A0\uFE0F Monitor is not running"));
    console.log(chalk.gray("Start with: stackmemory monitor --start"));
  }
}
async function showConfig(projectRoot) {
  const configFile = path.join(projectRoot, ".stackmemory", "config.json");
  console.log(chalk.bold("\n\u2699\uFE0F Monitor Configuration\n"));
  try {
    const config = JSON.parse(await fs.readFile(configFile, "utf-8"));
    const monitorConfig = config.monitor || {};
    console.log("Context Thresholds:");
    console.log(
      `  Warning: ${(monitorConfig.contextWarningThreshold || 0.6) * 100}%`
    );
    console.log(
      `  Critical: ${(monitorConfig.contextCriticalThreshold || 0.7) * 100}%`
    );
    console.log(
      `  Auto-save: ${(monitorConfig.contextAutoSaveThreshold || 0.85) * 100}%`
    );
    console.log("\nTimings:");
    console.log(
      `  Check interval: ${monitorConfig.checkIntervalSeconds || 30}s`
    );
    console.log(`  Idle timeout: ${monitorConfig.idleTimeoutMinutes || 5}min`);
    console.log("\nAuto Actions:");
    console.log(
      `  Auto-save ledger: ${monitorConfig.autoSaveLedger !== false ? "\u2705" : "\u274C"}`
    );
    console.log(
      `  Auto-generate handoff: ${monitorConfig.autoGenerateHandoff !== false ? "\u2705" : "\u274C"}`
    );
    console.log(
      `  Session-end handoff: ${monitorConfig.sessionEndHandoff !== false ? "\u2705" : "\u274C"}`
    );
  } catch {
    console.log(chalk.gray("Using default configuration"));
    console.log("\nDefaults:");
    console.log("  Warning at 60%, Critical at 70%, Auto-save at 85%");
    console.log("  Check every 30s, Idle timeout 5min");
    console.log("  All auto-actions enabled");
  }
}
async function updateActivity(projectRoot) {
  const activityFile = path.join(
    projectRoot,
    ".stackmemory",
    "monitor.activity"
  );
  await fs.mkdir(path.dirname(activityFile), { recursive: true });
  await fs.writeFile(activityFile, (/* @__PURE__ */ new Date()).toISOString(), "utf-8");
}
async function runDaemon(projectRoot, options) {
  const dbPath = path.join(projectRoot, ".stackmemory", "db", "stackmemory.db");
  const db = new Database(dbPath);
  const frameManager = new FrameManager(db, "current");
  const monitor = new SessionMonitor(frameManager, db, projectRoot, {
    checkIntervalSeconds: parseInt(options.interval) || 30,
    idleTimeoutMinutes: parseInt(options.idle) || 5,
    autoSaveLedger: true,
    autoGenerateHandoff: true,
    sessionEndHandoff: true
  });
  const statusFile = path.join(projectRoot, ".stackmemory", "monitor.status");
  const activityFile = path.join(
    projectRoot,
    ".stackmemory",
    "monitor.activity"
  );
  monitor.on("context:usage", async (data) => {
    try {
      const activityTime = await fs.readFile(activityFile, "utf-8");
      monitor.updateActivity();
    } catch {
    }
    const status = {
      lastCheck: (/* @__PURE__ */ new Date()).toISOString(),
      contextPercentage: data.percentage,
      contextStatus: data.status,
      lastActivity: monitor.getStatus().lastActivity
    };
    await fs.writeFile(statusFile, JSON.stringify(status, null, 2), "utf-8");
  });
  monitor.on("context:ledger_saved", async () => {
    const status = JSON.parse(await fs.readFile(statusFile, "utf-8"));
    status.lastLedgerSave = (/* @__PURE__ */ new Date()).toISOString();
    await fs.writeFile(statusFile, JSON.stringify(status, null, 2), "utf-8");
  });
  monitor.on("handoff:generated", async () => {
    const status = JSON.parse(await fs.readFile(statusFile, "utf-8"));
    status.lastHandoff = (/* @__PURE__ */ new Date()).toISOString();
    await fs.writeFile(statusFile, JSON.stringify(status, null, 2), "utf-8");
  });
  await monitor.start();
  process.on("SIGTERM", async () => {
    await monitor.stop();
    process.exit(0);
  });
}
async function runForeground(projectRoot, options) {
  console.log(chalk.bold("\u{1F50D} Running monitor in foreground...\n"));
  const dbPath = path.join(projectRoot, ".stackmemory", "db", "stackmemory.db");
  const db = new Database(dbPath);
  const frameManager = new FrameManager(db, "current");
  const monitor = new SessionMonitor(frameManager, db, projectRoot, {
    checkIntervalSeconds: parseInt(options.interval) || 30,
    idleTimeoutMinutes: parseInt(options.idle) || 5,
    autoSaveLedger: true,
    autoGenerateHandoff: true,
    sessionEndHandoff: true
  });
  monitor.on("context:usage", (data) => {
    console.log(
      `[${(/* @__PURE__ */ new Date()).toLocaleTimeString()}] Context: ${Math.round(data.percentage * 100)}% (${data.status})`
    );
  });
  monitor.on("context:warning", () => {
    console.log(chalk.yellow("\u26A0\uFE0F Context warning threshold reached"));
  });
  monitor.on("context:high", () => {
    console.log(chalk.yellow("\u{1F7E1} Context high - considering auto-save"));
  });
  monitor.on("context:ledger_saved", (data) => {
    console.log(
      chalk.green(`\u2705 Ledger saved (${data.compression}x compression)`)
    );
  });
  monitor.on("handoff:generated", (data) => {
    console.log(chalk.green(`\u{1F4CB} Handoff generated (${data.trigger})`));
  });
  await monitor.start();
  console.log("Press Ctrl+C to stop\n");
  process.on("SIGINT", async () => {
    console.log("\nStopping monitor...");
    await monitor.stop();
    process.exit(0);
  });
}
async function getProjectRoot() {
  return process.cwd();
}
function getStatusEmoji(status) {
  switch (status) {
    case "ok":
      return "\u{1F7E2}";
    case "warning":
      return "\u{1F7E1}";
    case "high":
      return "\u{1F7E0}";
    case "critical":
      return "\u{1F534}";
    default:
      return "\u26AB";
  }
}
var monitor_default = createMonitorCommand();
export {
  createMonitorCommand,
  monitor_default as default
};
//# sourceMappingURL=monitor.js.map
