"use strict";
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2024-2026 Gracker (Chris)
// This file is part of SmartPerfetto. See LICENSE for details.
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 () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.CodeLookupLedger = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const runtimePaths_1 = require("../../runtimePaths");
function defaultLedgerPath(sessionId) {
    return (0, runtimePaths_1.backendLogPath)(path.join('sessions', `${sessionId}.codeLookupLedger.jsonl`));
}
class CodeLookupLedger {
    constructor(sessionId, capTokens, capPatches, sidecarPath = defaultLedgerPath(sessionId)) {
        this.sessionId = sessionId;
        this.capTokens = capTokens;
        this.capPatches = capPatches;
        this.entries = [];
        this.appendQueue = Promise.resolve();
        this.sidecarPath = sidecarPath;
    }
    static restore(sessionId, capTokens, capPatches, sidecarPath = defaultLedgerPath(sessionId)) {
        const ledger = new CodeLookupLedger(sessionId, capTokens, capPatches, sidecarPath);
        if (!fs.existsSync(sidecarPath))
            return ledger;
        const raw = fs.readFileSync(sidecarPath, 'utf-8');
        for (const line of raw.split('\n')) {
            if (!line.trim())
                continue;
            ledger.entries.push(JSON.parse(line));
        }
        return ledger;
    }
    record(entry) {
        const normalized = {
            ...entry,
            ts: entry.ts || Date.now(),
            chunkIds: [...entry.chunkIds],
        };
        this.entries.push(normalized);
        this.appendQueue = this.appendQueue.then(async () => {
            const dir = path.dirname(this.sidecarPath);
            await fs.promises.mkdir(dir, { recursive: true });
            const handle = await fs.promises.open(this.sidecarPath, 'a');
            try {
                await handle.appendFile(`${JSON.stringify(normalized)}\n`, 'utf-8');
                await handle.sync();
            }
            finally {
                await handle.close();
            }
        });
    }
    async flush() {
        await this.appendQueue;
    }
    getEntries() {
        return this.entries;
    }
    hasPriorLookupOf(chunkId) {
        return this.entries.some(entry => entry.outcome === 'success' && entry.chunkIds.includes(chunkId));
    }
    hasSuccessfulCodeLookup() {
        return this.entries.some(entry => entry.outcome === 'success' && !entry.legacyPath && entry.chunkIds.length > 0);
    }
    remainingTokens() {
        const spent = this.entries.reduce((sum, entry) => sum + Math.max(0, entry.tokensSpent || 0), 0);
        return Math.max(0, this.capTokens - spent);
    }
    remainingPatches() {
        const spent = this.entries.filter(entry => entry.outcome === 'patch_verified' ||
            entry.outcome === 'patch_sketch' ||
            entry.outcome === 'patch_unverified').length;
        return Math.max(0, this.capPatches - spent);
    }
    toSnapshotSummary() {
        const codebaseIds = new Set();
        for (const entry of this.entries) {
            if (entry.codebaseId)
                codebaseIds.add(entry.codebaseId);
        }
        return {
            lookupCount: this.entries.filter(entry => entry.toolName !== 'propose_patch').length,
            patchCount: this.entries.filter(entry => entry.toolName === 'propose_patch').length,
            referencedCodebaseIds: Array.from(codebaseIds).sort(),
        };
    }
    getSessionId() {
        return this.sessionId;
    }
}
exports.CodeLookupLedger = CodeLookupLedger;
//# sourceMappingURL=codeLookupLedger.js.map