import { createDocumentStore } from "./state-backend.js";
export const MAX_SESSION_NAME_LENGTH = 30;
export class SessionNameStore {
    store;
    constructor(workspace, backend = "json") {
        this.store = createDocumentStore({
            workspace,
            fileName: "session-names.json",
            sqliteKey: "session-names",
            backend,
        });
    }
    get(agentId, threadId) {
        if (!agentId || !threadId) {
            return null;
        }
        const payload = normalizePayload(this.store.read());
        return payload.names[sessionNameKey(agentId, threadId)] ?? null;
    }
    set(agentId, threadId, rawName) {
        const name = sanitizeSessionName(rawName);
        let record = null;
        this.store.update((current) => {
            const payload = normalizePayload(current);
            const key = sessionNameKey(agentId, threadId);
            if (!name) {
                delete payload.names[key];
                return payload;
            }
            record = {
                agentId,
                threadId,
                name,
                updatedAt: new Date().toISOString(),
            };
            payload.names[key] = record;
            return payload;
        });
        return record;
    }
}
export function sanitizeSessionName(value) {
    return value.replace(/\s+/g, " ").trim().slice(0, MAX_SESSION_NAME_LENGTH);
}
function normalizePayload(payload) {
    if (!payload?.names || typeof payload.names !== "object") {
        return { version: 1, names: {} };
    }
    const names = {};
    for (const [key, record] of Object.entries(payload.names)) {
        const normalized = normalizeSessionNameRecord(record);
        if (normalized) {
            names[key] = normalized;
        }
    }
    return { version: 1, names };
}
function normalizeSessionNameRecord(record) {
    if (!record || !record.agentId || !record.threadId) {
        return null;
    }
    const name = sanitizeSessionName(String(record.name ?? ""));
    if (!name) {
        return null;
    }
    return {
        agentId: record.agentId,
        threadId: String(record.threadId),
        name,
        updatedAt: typeof record.updatedAt === "string" ? record.updatedAt : new Date().toISOString(),
    };
}
function sessionNameKey(agentId, threadId) {
    return `${agentId}:${threadId}`;
}
