/*
 * Copyright 2026, Jaime Terrats.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { existsSync, readdirSync, readFileSync, unlinkSync } from 'node:fs';
import { join } from 'node:path';
import { ensureDir, writeFileAtomic } from './file-writer.js';
const MAX_CONVERSATIONS = 50;
const MAX_MESSAGES = 200;
const MAX_MESSAGE_LENGTH = 32_768;
const VALID_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;
export function isValidConversationId(id) {
    return VALID_ID_PATTERN.test(id) && id.length > 0 && id.length <= 128;
}
function getHistoryDir(workspace) {
    return join(workspace, '.setup-agents', 'chat-history');
}
function getConversationPath(workspace, id) {
    return join(getHistoryDir(workspace), `${id}.json`);
}
/**
 * Lists all conversations in the workspace, returning metadata only (no messages).
 * Sorted by updatedAt descending (most recent first).
 */
export function listConversations(workspace) {
    const dir = getHistoryDir(workspace);
    if (!existsSync(dir))
        return [];
    const files = readdirSync(dir).filter((f) => f.endsWith('.json'));
    const conversations = [];
    for (const file of files) {
        try {
            const content = readFileSync(join(dir, file), 'utf8');
            const conv = JSON.parse(content);
            conversations.push({
                id: conv.id,
                title: conv.title,
                createdAt: conv.createdAt,
                updatedAt: conv.updatedAt,
                messageCount: conv.messageCount,
            });
        }
        catch {
            // Skip malformed files
        }
    }
    return conversations.sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());
}
/**
 * Loads a full conversation by id, including messages.
 * Returns null if not found.
 */
export function loadConversation(workspace, id) {
    const filePath = getConversationPath(workspace, id);
    if (!existsSync(filePath))
        return null;
    try {
        const content = readFileSync(filePath, 'utf8');
        return JSON.parse(content);
    }
    catch {
        return null;
    }
}
/**
 * Saves or updates a conversation. Enforces message limit per conversation
 * and conversation count limit per workspace.
 */
export function saveConversation(workspace, id, title, messages) {
    const dir = getHistoryDir(workspace);
    ensureDir(dir);
    const filePath = getConversationPath(workspace, id);
    const existing = loadConversation(workspace, id);
    const now = new Date().toISOString();
    // Truncate messages to the limit and enforce per-message size
    const truncatedMessages = messages.slice(-MAX_MESSAGES).map((m) => ({
        ...m,
        content: m.content.length > MAX_MESSAGE_LENGTH ? m.content.slice(0, MAX_MESSAGE_LENGTH) : m.content,
    }));
    const conversation = {
        id,
        title,
        messages: truncatedMessages,
        createdAt: existing?.createdAt ?? now,
        updatedAt: now,
        messageCount: truncatedMessages.length,
    };
    writeFileAtomic(filePath, JSON.stringify(conversation, null, 2) + '\n');
    // Enforce max conversations: evict oldest if over limit
    if (!existing) {
        evictOldConversations(workspace);
    }
    return conversation;
}
/**
 * Deletes a conversation by id.
 * Returns true if the conversation was found and deleted.
 */
export function deleteConversation(workspace, id) {
    const filePath = getConversationPath(workspace, id);
    if (!existsSync(filePath))
        return false;
    try {
        unlinkSync(filePath);
        return true;
    }
    catch {
        return false;
    }
}
/**
 * Evicts the oldest conversations when over the limit.
 */
function evictOldConversations(workspace) {
    const all = listConversations(workspace);
    if (all.length <= MAX_CONVERSATIONS)
        return;
    // Remove oldest (they come last since list is sorted desc)
    const toRemove = all.slice(MAX_CONVERSATIONS);
    for (const conv of toRemove) {
        deleteConversation(workspace, conv.id);
    }
}
//# sourceMappingURL=chat-history.js.map