import { join } from "node:path";
import { getAgentDir } from "../config.js";
import { FileAuthStorageBackend } from "./auth-storage-backends.js";
export class InMemoryCodingAgentModelsStore {
    constructor() {
        this.entries = new Map();
    }
    async read(providerId) {
        const entry = this.entries.get(providerId);
        return entry === undefined ? undefined : structuredClone(entry);
    }
    async write(providerId, entry) {
        this.entries.set(providerId, structuredClone(entry));
    }
    async delete(providerId) {
        this.entries.delete(providerId);
    }
    async writeIf(providerId, entry, predicate) {
        if (predicate())
            await this.write(providerId, entry);
    }
    async deleteIf(providerId, predicate) {
        if (predicate())
            await this.delete(providerId);
    }
}
/** Locked JSON-backed storage for dynamically refreshed provider catalogs. */
export class FileModelsStore {
    constructor(path = join(getAgentDir(), "models-store.json")) {
        this.storage = new FileAuthStorageBackend(path);
    }
    parse(content) {
        return content ? JSON.parse(content) : {};
    }
    async read(providerId) {
        return this.storage.withLock((content) => ({
            result: structuredClone(this.parse(content)[providerId]),
        }));
    }
    async write(providerId, entry) {
        await this.storage.withLockAsync(async (content) => {
            const current = this.parse(content);
            current[providerId] = structuredClone(entry);
            return { result: undefined, next: JSON.stringify(current, null, 2) };
        });
    }
    async delete(providerId) {
        await this.storage.withLockAsync(async (content) => {
            const current = this.parse(content);
            delete current[providerId];
            return { result: undefined, next: JSON.stringify(current, null, 2) };
        });
    }
    async writeIf(providerId, entry, predicate) {
        await this.storage.withLockAsync(async (content) => {
            if (!predicate())
                return { result: undefined };
            const current = this.parse(content);
            current[providerId] = structuredClone(entry);
            return { result: undefined, next: JSON.stringify(current, null, 2) };
        });
    }
    async deleteIf(providerId, predicate) {
        await this.storage.withLockAsync(async (content) => {
            if (!predicate())
                return { result: undefined };
            const current = this.parse(content);
            delete current[providerId];
            return { result: undefined, next: JSON.stringify(current, null, 2) };
        });
    }
}
//# sourceMappingURL=models-store.js.map