import fs from "node:fs";
import path from "node:path";
export function setSessionTitle(dataDir, sessionId, title) {
    const metadata = readAllMetadata(dataDir);
    const previous = metadata[sessionId];
    const record = {
        sessionId,
        title: title.trim(),
        tags: previous?.tags ?? [],
        updatedAtMs: Date.now(),
    };
    metadata[sessionId] = record;
    writeAllMetadata(dataDir, metadata);
    return record;
}
export function getSessionTitle(dataDir, sessionId) {
    return readAllMetadata(dataDir)[sessionId]?.title;
}
export function listSessionTitles(dataDir) {
    return readAllMetadata(dataDir);
}
export function toggleSessionTag(dataDir, sessionId, tag) {
    const normalized = normalizeSessionTag(tag);
    if (!normalized)
        throw new Error("tag name cannot be empty");
    const metadata = readAllMetadata(dataDir);
    const previous = metadata[sessionId];
    const tags = new Set(previous?.tags ?? []);
    if (tags.has(normalized)) {
        tags.delete(normalized);
    }
    else {
        tags.add(normalized);
    }
    const record = {
        sessionId,
        title: previous?.title ?? "",
        tags: [...tags].sort(),
        updatedAtMs: Date.now(),
    };
    metadata[sessionId] = record;
    writeAllMetadata(dataDir, metadata);
    return record;
}
export function setSessionTags(dataDir, sessionId, tags) {
    const metadata = readAllMetadata(dataDir);
    const previous = metadata[sessionId];
    const normalized = Array.from(new Set(tags.map(normalizeSessionTag).filter(Boolean))).sort();
    const record = {
        sessionId,
        title: previous?.title ?? "",
        tags: normalized,
        updatedAtMs: Date.now(),
    };
    metadata[sessionId] = record;
    writeAllMetadata(dataDir, metadata);
    return record;
}
export function getSessionTags(dataDir, sessionId) {
    return readAllMetadata(dataDir)[sessionId]?.tags ?? [];
}
export function normalizeSessionTag(value) {
    return value
        .trim()
        .toLowerCase()
        .replace(/^#+/, "")
        .replace(/[^a-z0-9._-]+/g, "-")
        .replace(/^-+|-+$/g, "")
        .slice(0, 48);
}
function metadataPath(dataDir) {
    return path.join(dataDir, "sessions", "metadata.json");
}
function readAllMetadata(dataDir) {
    const filePath = metadataPath(dataDir);
    if (!fs.existsSync(filePath))
        return {};
    try {
        const parsed = JSON.parse(fs.readFileSync(filePath, "utf8"));
        return Object.fromEntries(Object.entries(parsed).map(([sessionId, record]) => [
            sessionId,
            {
                sessionId: record.sessionId ?? sessionId,
                title: record.title ?? "",
                tags: Array.isArray(record.tags) ? record.tags.map(normalizeSessionTag).filter(Boolean) : [],
                updatedAtMs: Number(record.updatedAtMs ?? 0),
            },
        ]));
    }
    catch {
        return {};
    }
}
function writeAllMetadata(dataDir, metadata) {
    const filePath = metadataPath(dataDir);
    fs.mkdirSync(path.dirname(filePath), { recursive: true });
    fs.writeFileSync(filePath, JSON.stringify(metadata, null, 2), "utf8");
}
