import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
import {
  DEFAULT_LOG_TAIL,
  matchesFilter,
  queryLogs
} from "./chunk-H7PRCVGQ.js";
import {
  LEVEL_ORDER
} from "./chunk-QLUE3BUL.js";
import {
  formatLogLine,
  parseIntFlag,
  parseStringFlag
} from "./chunk-SAKJMNSR.js";
import "./chunk-PZUWP5VK.js";

// src/cli/logs.ts
import fs from "fs";
import path from "path";
var FOLLOW_POLL_INTERVAL_MS = 500;
function run(args, vaultDir) {
  const logDir = path.join(vaultDir, "logs");
  const follow = args.includes("--follow") || args.includes("-f");
  const limit = parseIntFlag(args, "--tail", "-n") ?? DEFAULT_LOG_TAIL;
  const rawLevel = parseStringFlag(args, "--level", "-l");
  if (rawLevel && !(rawLevel in LEVEL_ORDER)) {
    console.error(`Invalid level: ${rawLevel}. Valid levels: ${Object.keys(LEVEL_ORDER).join(", ")}`);
    process.exit(1);
  }
  const level = rawLevel;
  const component = parseStringFlag(args, "--component", "-c");
  const since = parseStringFlag(args, "--since");
  const until = parseStringFlag(args, "--until");
  const result = queryLogs(logDir, { limit, level, component, since, until });
  for (const e of result.entries) {
    process.stdout.write(formatLogLine(e) + "\n");
  }
  if (result.truncated) {
    process.stdout.write(`  ... ${result.total - result.entries.length} earlier entries omitted
`);
  }
  if (!follow) return;
  const followFilter = { level, component, until };
  const logPath = path.join(logDir, "daemon.log");
  let offset = 0;
  try {
    offset = fs.statSync(logPath).size;
  } catch {
  }
  fs.watchFile(logPath, { interval: FOLLOW_POLL_INTERVAL_MS }, (curr, prev) => {
    if (curr.size < prev.size || curr.ino !== prev.ino) {
      offset = 0;
    }
    if (curr.size <= offset) return;
    try {
      const fd = fs.openSync(logPath, "r");
      const buf = Buffer.alloc(curr.size - offset);
      fs.readSync(fd, buf, 0, buf.length, offset);
      fs.closeSync(fd);
      const text = buf.toString("utf-8");
      const lastNewline = text.lastIndexOf("\n");
      if (lastNewline < 0) return;
      offset += Buffer.byteLength(text.slice(0, lastNewline + 1));
      for (const line of text.slice(0, lastNewline).split("\n")) {
        if (!line.trim()) continue;
        try {
          const e = JSON.parse(line);
          if (!matchesFilter(e, followFilter)) continue;
          process.stdout.write(formatLogLine(e) + "\n");
        } catch {
        }
      }
    } catch {
    }
  });
  process.on("SIGINT", () => {
    fs.unwatchFile(logPath);
    process.exit(0);
  });
}
export {
  run
};
//# sourceMappingURL=logs-IENORIYR.js.map