import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { readJsonLines } from "./json-lines.js";
export class LocalEvidenceStore {
    #threads;
    constructor(threads) {
        this.#threads = threads;
    }
    async append(threadId, evidence) {
        this.#ensureEvidenceDirectory(threadId);
        const existing = readJsonLines(this.#cardsPath(threadId));
        if (existing.some((candidate) => candidate.evidenceId === evidence.evidenceId)) {
            return false;
        }
        appendFileSync(this.#cardsPath(threadId), `${JSON.stringify(evidence)}\n`);
        this.#writeIndex(threadId, [...existing, evidence]);
        return true;
    }
    async list(input) {
        const evidence = readJsonLines(this.#cardsPath(input.threadId));
        const evidenceIds = input.evidenceIds ? new Set(input.evidenceIds) : undefined;
        return evidence.filter((candidate) => {
            if (input.kind && candidate.kind !== input.kind) {
                return false;
            }
            if (input.runId && candidate.runId !== input.runId) {
                return false;
            }
            if (input.turnId && candidate.turnId !== input.turnId) {
                return false;
            }
            if (input.filePath && !candidate.relatedFilePaths?.includes(input.filePath)) {
                return false;
            }
            if (evidenceIds && !evidenceIds.has(candidate.evidenceId)) {
                return false;
            }
            return true;
        });
    }
    #ensureEvidenceDirectory(threadId) {
        mkdirSync(this.#evidenceDir(threadId), { recursive: true });
    }
    #writeIndex(threadId, evidence) {
        const byKind = evidence.reduce((counts, candidate) => {
            counts[candidate.kind] = (counts[candidate.kind] ?? 0) + 1;
            return counts;
        }, {});
        const index = {
            byKind,
            latestCreatedAt: evidence.at(-1)?.createdAt,
            totalCount: evidence.length,
            updatedAt: new Date().toISOString(),
        };
        writeFileSync(this.#indexPath(threadId), JSON.stringify(index, null, 2));
    }
    #evidenceDir(threadId) {
        return join(this.#threads.getThreadPaths(threadId).threadDir, "evidence");
    }
    #cardsPath(threadId) {
        return join(this.#evidenceDir(threadId), "cards.jsonl");
    }
    #indexPath(threadId) {
        return join(this.#evidenceDir(threadId), "index.json");
    }
}
//# sourceMappingURL=evidence-store.js.map