import { SessionStorage } from "./sessionStorage.js";
import { getSessionTags, getSessionTitle } from "./sessionMetadata.js";
export function resumeSession(state, dataDir, projectPath, sessionId, limit = 24) {
    const records = new SessionStorage(dataDir, sessionId).readAll(limit);
    if (records.length === 0) {
        throw new Error(`No transcript records for ${sessionId}.`);
    }
    state.setUiState(sessionScope(projectPath), "current_session_id", sessionId);
    state.appendEvent(null, "session_resumed", { session_id: sessionId, project_path: projectPath });
    return {
        sessionId,
        title: getSessionTitle(dataDir, sessionId),
        tags: getSessionTags(dataDir, sessionId),
        records,
    };
}
export function getCurrentSessionId(state, projectPath) {
    return state.getUiState(sessionScope(projectPath), "current_session_id");
}
export function setCurrentSessionId(state, projectPath, sessionId) {
    state.setUiState(sessionScope(projectPath), "current_session_id", sessionId);
}
export function clearCurrentSession(state, projectPath) {
    state.deleteUiState(sessionScope(projectPath), "current_session_id");
}
export function formatResumeSessionPreview(preview) {
    return [
        `resumed session: ${preview.sessionId}${preview.title ? ` (${preview.title})` : ""}${preview.tags?.length ? ` ${preview.tags.map((tag) => `#${tag}`).join(" ")}` : ""}`,
        ...preview.records.map((record) => `${record.role}: ${firstLine(record.text)}`),
    ].join("\n");
}
function sessionScope(projectPath) {
    return `session:${projectPath}`;
}
function firstLine(value) {
    const line = value.split(/\r?\n/)[0]?.trim() ?? "";
    return line.length > 180 ? `${line.slice(0, 177)}...` : line;
}
