import { createRequire as __cr } from 'node:module'; const require = __cr(import.meta.url);
import {
  LEVEL_ORDER
} from "./chunk-QLUE3BUL.js";

// src/logs/reader.ts
import fs from "fs";
import path from "path";
var DEFAULT_LOG_TAIL = 50;
var MAX_LOG_QUERY_LIMIT = 1e4;
var DAEMON_LOG_PATTERN = /^daemon(?:\.(\d+))?\.log$/;
var MCP_LOG_FILE = "mcp.jsonl";
function queryLogs(logDir, query = {}) {
  const limit = Math.min(query.limit ?? DEFAULT_LOG_TAIL, MAX_LOG_QUERY_LIMIT);
  const logFiles = discoverLogFiles(logDir);
  if (logFiles.length === 0) {
    return { entries: [], total: 0, truncated: false };
  }
  const allEntries = readAndParse(logFiles);
  allEntries.sort((a, b) => (a.timestamp ?? "").localeCompare(b.timestamp ?? ""));
  const filtered = applyFilters(allEntries, query);
  const total = filtered.length;
  const truncated = total > limit;
  const entries = truncated ? filtered.slice(total - limit) : filtered;
  return { entries, total, truncated };
}
function discoverLogFiles(logDir) {
  let files;
  try {
    files = fs.readdirSync(logDir);
  } catch {
    return [];
  }
  const matched = [];
  for (const file of files) {
    if (file === MCP_LOG_FILE) {
      matched.push({ path: path.join(logDir, file), order: -1 });
      continue;
    }
    const m = DAEMON_LOG_PATTERN.exec(file);
    if (!m) continue;
    const rotationNum = m[1] ? parseInt(m[1], 10) : 0;
    matched.push({ path: path.join(logDir, file), order: rotationNum });
  }
  matched.sort((a, b) => {
    if (a.order === 0) return 1;
    if (b.order === 0) return -1;
    return b.order - a.order;
  });
  return matched.map((m) => m.path);
}
function readAndParse(filePaths) {
  const entries = [];
  for (const filePath of filePaths) {
    let content;
    try {
      content = fs.readFileSync(filePath, "utf-8");
    } catch {
      continue;
    }
    for (const line of content.split("\n")) {
      if (!line.trim()) continue;
      try {
        entries.push(JSON.parse(line));
      } catch {
      }
    }
  }
  return entries;
}
function matchesFilter(entry, query) {
  if (query.level) {
    const entryOrder = LEVEL_ORDER[entry.level] ?? 0;
    const minOrder = LEVEL_ORDER[query.level];
    if (entryOrder < minOrder) return false;
  }
  if (query.component && entry.component !== query.component) return false;
  if (query.since && entry.timestamp < query.since) return false;
  if (query.until && entry.timestamp > query.until) return false;
  return true;
}
function applyFilters(entries, query) {
  return entries.filter((entry) => matchesFilter(entry, query));
}

export {
  DEFAULT_LOG_TAIL,
  queryLogs,
  matchesFilter
};
//# sourceMappingURL=chunk-H7PRCVGQ.js.map