"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TelemetryWriter = void 0;
const node_fs_1 = require("node:fs");
const promises_1 = require("node:fs/promises");
const node_path_1 = require("node:path");
/**
 * Append-only JSONL telemetry writer with daily file rotation.
 *
 * File pattern: `${basePath}/telemetry-YYYY-MM-DD.jsonl`
 *
 * No npm dependencies — uses only Node.js built-ins.
 */
class TelemetryWriter {
    basePath;
    initialized = false;
    constructor(basePath) {
        this.basePath = basePath;
    }
    /**
     * Sync append — used by synchronous gates (Gate 1, Gate 2).
     */
    record(decision) {
        this.ensureDir();
        const line = JSON.stringify(decision) + "\n";
        (0, node_fs_1.appendFileSync)(this.getFilePath(), line, "utf-8");
    }
    /**
     * Async append — used by async gates (Gate 3, Gate 4).
     */
    async recordAsync(decision) {
        this.ensureDir();
        const line = JSON.stringify(decision) + "\n";
        await (0, promises_1.appendFile)(this.getFilePath(), line, "utf-8");
    }
    /**
     * Returns the file path for today's telemetry file.
     */
    getFilePath(date) {
        const d = date ?? new Date();
        const yyyy = d.getFullYear();
        const mm = String(d.getMonth() + 1).padStart(2, "0");
        const dd = String(d.getDate()).padStart(2, "0");
        return (0, node_path_1.join)(this.basePath, `telemetry-${yyyy}-${mm}-${dd}.jsonl`);
    }
    /**
     * Read the last N decisions from today's file.
     * Returns empty array if file doesn't exist or is empty.
     */
    readRecent(n, date) {
        const filePath = this.getFilePath(date);
        if (!(0, node_fs_1.existsSync)(filePath))
            return [];
        let content;
        try {
            content = (0, node_fs_1.readFileSync)(filePath, "utf-8");
        }
        catch {
            return [];
        }
        const lines = content.trim().split("\n").filter(Boolean);
        const recent = lines.slice(-n);
        const decisions = [];
        for (const line of recent) {
            try {
                decisions.push(JSON.parse(line));
            }
            catch {
                // Skip malformed lines
            }
        }
        return decisions;
    }
    /**
     * Quick stats from today's file.
     */
    countToday(date) {
        const filePath = this.getFilePath(date);
        if (!(0, node_fs_1.existsSync)(filePath))
            return { total: 0, threats: 0, blocked: 0 };
        let content;
        try {
            content = (0, node_fs_1.readFileSync)(filePath, "utf-8");
        }
        catch {
            return { total: 0, threats: 0, blocked: 0 };
        }
        const lines = content.trim().split("\n").filter(Boolean);
        let total = 0;
        let threats = 0;
        let blocked = 0;
        for (const line of lines) {
            try {
                const d = JSON.parse(line);
                total++;
                if (d.is_threat)
                    threats++;
                if (d.action === "blocked" || d.action === "quarantined" || d.action === "cancelled") {
                    blocked++;
                }
            }
            catch {
                // Skip malformed lines
            }
        }
        return { total, threats, blocked };
    }
    ensureDir() {
        if (this.initialized)
            return;
        (0, node_fs_1.mkdirSync)(this.basePath, { recursive: true });
        this.initialized = true;
    }
}
exports.TelemetryWriter = TelemetryWriter;
