import { DEFAULT_AGENT_GENERATION_SETTINGS, normalizeAgentGenerationSettings, } from "./agentSettings.js";
export function cleanString(value, fallback = "") {
    if (typeof value !== "string")
        return fallback;
    return value.trim().slice(0, 10_000) || fallback;
}
export function parseStringArray(value) {
    try {
        const parsed = JSON.parse(value);
        return Array.isArray(parsed) ? parsed.filter((item) => typeof item === "string") : [];
    }
    catch {
        return [];
    }
}
export function parseJsonObject(value) {
    try {
        const parsed = JSON.parse(value);
        return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
    }
    catch {
        return {};
    }
}
export function parseToolCalls(raw) {
    const toolCalls = parseJsonObject(raw).toolCalls;
    if (!Array.isArray(toolCalls))
        return undefined;
    return toolCalls.filter((item) => (item &&
        typeof item === "object" &&
        typeof item.id === "string" &&
        typeof item.name === "string"));
}
export function jsonStringArray(values) {
    return JSON.stringify(Array.isArray(values) ? values.filter(Boolean) : []);
}
export function cleanStringArray(values) {
    if (!Array.isArray(values))
        return [];
    return values.filter((value) => typeof value === "string" && value.trim()).map((value) => value.trim());
}
export function sessionFromRow(row) {
    return {
        id: row.id,
        title: row.title,
        codexThreadId: row.codexThreadId,
        lastTurnId: row.lastTurnId,
        lastImageId: row.currentImageId,
        imageCount: row.imageCount,
        compacted: row.compacted === 1,
        webSearchEnabled: row.webSearchEnabled === 1,
        generationSettings: normalizeAgentGenerationSettings(parseJsonObject(row.generationSettings), { ...DEFAULT_AGENT_GENERATION_SETTINGS, webSearchEnabled: row.webSearchEnabled === 1 }),
        updatedAt: row.updatedAt,
    };
}
export function turnFromRow(row) {
    return {
        id: row.id,
        role: row.role,
        text: row.text,
        status: row.status,
        imageIds: parseStringArray(row.imageIds),
        webFindingIds: parseStringArray(row.webFindingIds),
        toolCalls: parseToolCalls(row.raw),
        createdAt: row.createdAt,
    };
}
export function imageFromRow(row) {
    return {
        id: row.id,
        filename: row.filename,
        url: row.url,
        thumbUrl: row.thumbUrl,
        prompt: row.prompt,
        revisedPrompt: row.revisedPrompt,
        width: row.width,
        height: row.height,
        createdAt: row.createdAt,
    };
}
