import { readDocument, readDocumentReadonly, writeScope } from "./store.js";
const SCOPE = "models";
const DEFAULT_KEY = "default";
export async function loadAgentModel(options, agentId) {
    const models = await readModelsScope(options);
    const value = getOwnEntry(models, agentId);
    return typeof value === "string" ? value : null;
}
export async function loadDefaultModel(options) {
    const models = await readModelsScope(options);
    const value = getOwnEntry(models, DEFAULT_KEY);
    return typeof value === "string" ? value : null;
}
export async function resolveModel(options, agentId) {
    return (await loadAgentModel(options, agentId)) ?? await loadDefaultModel(options);
}
export async function saveAgentModel(options, agentId, model) {
    const models = await readModelsScope(options);
    await writeScope(options.fs, options.filePath, SCOPE, {
        ...models,
        [agentId]: model
    });
}
export async function saveDefaultModel(options, model) {
    const models = await readModelsScope(options);
    await writeScope(options.fs, options.filePath, SCOPE, {
        ...models,
        [DEFAULT_KEY]: model
    });
}
async function readModelsScope(options) {
    const readConfigDocument = getOwnEntry(options, "readOnly")
        ? readDocumentReadonly
        : readDocument;
    const document = await readConfigDocument(options.fs, options.filePath);
    return getOwnRecordEntry(document, SCOPE);
}
function getOwnEntry(record, key) {
    return Object.prototype.hasOwnProperty.call(record, key) ? record[key] : undefined;
}
function getOwnRecordEntry(record, key) {
    const value = getOwnEntry(record, key);
    return value !== null && typeof value === "object" && !Array.isArray(value)
        ? value
        : {};
}
