/**
 * 终端会话持久化服务
 *
 * 管理终端会话元数据的持久化存储
 */
import { promises as fs } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { atomicWriteJsonFile, withFileLock } from '../utils/file-utils.js';
import { createLogger } from '../utils/logger.js';
const log = createLogger('terminal-persistence');
async function readAllPersistedSessions(filePath) {
    try {
        const raw = await fs.readFile(filePath, 'utf-8');
        return JSON.parse(raw);
    }
    catch (error) {
        const err = error;
        if (err.code !== 'ENOENT') {
            log.warn(`[readAllPersistedSessions] 读取持久化会话失败: ${filePath}, error=${err.message}`);
        }
        return [];
    }
}
async function updatePersistedSessions(updater) {
    const filePath = getPersistedSessionsFile();
    await withFileLock(filePath, async () => {
        const sessions = await readAllPersistedSessions(filePath);
        const nextSessions = await updater(sessions);
        await atomicWriteJsonFile(filePath, nextSessions);
    });
}
/**
 * 获取持久化会话文件路径
 *
 * @returns 会话文件路径
 */
export function getPersistedSessionsFile() {
    return path.join(os.tmpdir(), 'agentswork-runtime-bridge', 'sessions.json');
}
/**
 * 加载持久化的终端会话列表
 *
 * @returns 持久化会话列表
 */
export async function loadPersistedSessions() {
    const filePath = getPersistedSessionsFile();
    return withFileLock(filePath, async () => {
        const sessions = await readAllPersistedSessions(filePath);
        // 只返回状态为 running 的会话
        return sessions.filter(s => s.status === 'running');
    });
}
/**
 * 保存持久化的终端会话列表
 *
 * @param sessions - 会话列表
 */
export async function savePersistedSessions(sessions) {
    const filePath = getPersistedSessionsFile();
    await withFileLock(filePath, async () => {
        await atomicWriteJsonFile(filePath, sessions);
    });
}
/**
 * 添加或更新持久化会话
 *
 * @param session - 会话数据
 */
export async function upsertPersistedSession(session) {
    await updatePersistedSessions((sessions) => {
        const runningSessions = sessions
            .filter(s => s.status === 'running')
            .filter(s => s.sessionId !== session.sessionId && s.agentId !== session.agentId);
        runningSessions.push(session);
        return runningSessions;
    });
}
/**
 * 更新指定 Agent 的持久化自动命令配置。
 *
 * 主流程：加载 running 会话 -> 命中 agentId 时只替换自动命令字段，保留原 command/workspace/pid。
 */
export async function updatePersistedSessionAutoCommands(agentId, commands) {
    let updated = false;
    await updatePersistedSessions((sessions) => sessions.map((session) => {
        if (session.agentId !== agentId) {
            return session;
        }
        updated = true;
        return {
            ...session,
            idleInputAutoCommand: commands.idleInputAutoCommand,
            nonInputAutoCommand: commands.nonInputAutoCommand,
        };
    }));
    return updated;
}
/**
 * 移除持久化会话（从完整文件中删除，包括 stopped 状态的）
 *
 * @param sessionId - 会话 ID
 */
export async function removePersistedSession(sessionId) {
    const filePath = getPersistedSessionsFile();
    await withFileLock(filePath, async () => {
        const allSessions = await readAllPersistedSessions(filePath);
        const beforeCount = allSessions.length;
        const filtered = allSessions.filter(s => s.sessionId !== sessionId);
        const afterCount = filtered.length;
        if (beforeCount !== afterCount) {
            log.info(`[removePersistedSession] 删除持久化会话: sessionId=${sessionId}, 删除前=${beforeCount}, 删除后=${afterCount}`);
        }
        else {
            log.warn(`[removePersistedSession] 未找到要删除的会话: sessionId=${sessionId}, 当前会话数=${beforeCount}`);
        }
        await atomicWriteJsonFile(filePath, filtered);
    });
}
/**
 * 根据 agentId 查找持久化会话
 *
 * @param agentId - Agent ID
 * @returns 持久化会话，未找到返回 undefined
 */
export async function findPersistedSessionByAgentId(agentId) {
    const sessions = await loadPersistedSessions();
    return sessions
        .filter(s => s.agentId === agentId)
        .sort((a, b) => String(b.startedAt || '').localeCompare(String(a.startedAt || '')))[0];
}
/**
 * 根据 agentId 移除持久化会话
 * 用于确保停止时能删除正确的持久化会话
 *
 * @param agentId - Agent ID
 */
export async function removePersistedSessionByAgentId(agentId) {
    const filePath = getPersistedSessionsFile();
    await withFileLock(filePath, async () => {
        const allSessions = await readAllPersistedSessions(filePath);
        const beforeCount = allSessions.length;
        const filtered = allSessions.filter(s => s.agentId !== agentId);
        const afterCount = filtered.length;
        if (beforeCount !== afterCount) {
            log.info(`[removePersistedSessionByAgentId] 删除持久化会话: agentId=${agentId}, 删除前=${beforeCount}, 删除后=${afterCount}`);
        }
        else {
            log.debug(`[removePersistedSessionByAgentId] 未找到要删除的会话: agentId=${agentId}`);
        }
        await atomicWriteJsonFile(filePath, filtered);
    });
}
