"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizeLogQueryLevel = exports.readLogSourceSummaries = exports.readLogEntries = void 0;
const fs = __importStar(require("fs"));
const log_buffer_1 = require("./log-buffer");
const log_paths_1 = require("./log-paths");
const log_types_1 = require("./log-types");
let currentLogCache = null;
function parseLogLine(line) {
    try {
        return JSON.parse(line);
    }
    catch {
        return null;
    }
}
function readCurrentFileEntries() {
    const currentLogPath = (0, log_paths_1.getCurrentLogPath)();
    if (!fs.existsSync(currentLogPath)) {
        currentLogCache = null;
        return [];
    }
    const stats = fs.statSync(currentLogPath, { bigint: true });
    if (currentLogCache &&
        currentLogCache.path === currentLogPath &&
        currentLogCache.mtimeNs === stats.mtimeNs &&
        currentLogCache.size === stats.size) {
        return [...currentLogCache.entries];
    }
    const entries = fs
        .readFileSync(currentLogPath, 'utf8')
        .split('\n')
        .map((line) => line.trim())
        .filter(Boolean)
        .map(parseLogLine)
        .filter((entry) => entry !== null);
    currentLogCache = {
        entries,
        mtimeNs: stats.mtimeNs,
        path: currentLogPath,
        size: stats.size,
    };
    return [...entries];
}
function matchesLogQuery(entry, options) {
    if (options.source && entry.source !== options.source) {
        return false;
    }
    if (options.level && entry.level !== options.level) {
        return false;
    }
    if (!options.search) {
        return true;
    }
    const search = options.search.toLowerCase();
    return (entry.message.toLowerCase().includes(search) ||
        entry.event.toLowerCase().includes(search) ||
        entry.source.toLowerCase().includes(search) ||
        String(entry.processId).toLowerCase().includes(search) ||
        entry.runId.toLowerCase().includes(search) ||
        JSON.stringify(entry.context || {})
            .toLowerCase()
            .includes(search));
}
function dedupeEntries(entries) {
    const seen = new Map();
    for (const entry of entries) {
        seen.set(entry.id, entry);
    }
    return [...seen.values()];
}
function readLogEntries(options = {}) {
    const limit = options.limit ?? 200;
    const entries = dedupeEntries([...readCurrentFileEntries(), ...(0, log_buffer_1.getRecentLogEntries)()])
        .filter((entry) => matchesLogQuery(entry, options))
        .sort((a, b) => Date.parse(b.timestamp) - Date.parse(a.timestamp));
    return entries.slice(0, limit);
}
exports.readLogEntries = readLogEntries;
function readLogSourceSummaries() {
    const summaryMap = new Map();
    for (const entry of readLogEntries({ limit: 500 })) {
        const current = summaryMap.get(entry.source) ?? {
            source: entry.source,
            label: entry.source,
            kind: 'native',
            count: 0,
            lastTimestamp: null,
        };
        current.count += 1;
        current.lastTimestamp = current.lastTimestamp ?? entry.timestamp;
        summaryMap.set(entry.source, current);
    }
    return [...summaryMap.values()].sort((a, b) => a.label.localeCompare(b.label));
}
exports.readLogSourceSummaries = readLogSourceSummaries;
function normalizeLogQueryLevel(level) {
    return (0, log_types_1.isLoggingLevel)(level) ? level : undefined;
}
exports.normalizeLogQueryLevel = normalizeLogQueryLevel;
//# sourceMappingURL=log-reader.js.map