/**
 * 实例状态持久化服务
 *
 * 管理 Agent 实例的初始化状态持久化
 */
import { promises as fs } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { getRuntimeHomeDir } from '../config.js';
import { atomicWriteJsonFile, ensureDir } from '../utils/file-utils.js';
import { ensureEnabledTools, parseBoolean } from '../utils/validation.js';
function getLegacyInstanceStateFile(agentId) {
    return path.join(os.tmpdir(), 'agentswork-runtime-init', String(agentId), 'state.json');
}
function createDefaultInstanceState() {
    return {
        initialized: false,
        skills: [],
        mcpServers: [],
        enabledTools: ['acode', 'claude', 'opencode', 'codex'],
        toolStatus: {},
        skillEnabled: true,
        mcpEnabled: true,
        updatedAt: null,
    };
}
/**
 * 获取实例状态文件路径
 *
 * @param agentId - Agent ID
 * @returns 状态文件路径
 */
export function getInstanceStateFile(agentId) {
    return path.join(getRuntimeHomeDir(), '.aws-bridge', 'instances', String(agentId), 'state.json');
}
/**
 * 加载实例状态
 *
 * @param agentId - Agent ID
 * @returns 实例状态
 */
export async function loadInstanceState(agentId) {
    const filePath = getInstanceStateFile(agentId);
    const legacyFilePath = getLegacyInstanceStateFile(agentId);
    try {
        const raw = await fs.readFile(filePath, 'utf-8');
        return JSON.parse(raw);
    }
    catch {
        try {
            const raw = await fs.readFile(legacyFilePath, 'utf-8');
            const legacyState = JSON.parse(raw);
            await atomicWriteJsonFile(filePath, legacyState);
            return legacyState;
        }
        catch {
            return createDefaultInstanceState();
        }
    }
}
/**
 * 保存实例状态
 *
 * @param agentId - Agent ID
 * @param state - 部分实例状态
 * @returns 完整的实例状态
 */
export async function saveInstanceState(agentId, state) {
    const filePath = getInstanceStateFile(agentId);
    await ensureDir(path.dirname(filePath));
    const next = {
        initialized: Boolean(state?.initialized),
        skills: Array.isArray(state?.skills) ? state.skills : [],
        mcpServers: Array.isArray(state?.mcpServers) ? state.mcpServers : [],
        enabledTools: ensureEnabledTools(state?.enabledTools),
        toolStatus: state?.toolStatus && typeof state.toolStatus === 'object' && !Array.isArray(state.toolStatus)
            ? state.toolStatus
            : {},
        skillEnabled: parseBoolean(state?.skillEnabled, true),
        mcpEnabled: parseBoolean(state?.mcpEnabled, true),
        updatedAt: new Date().toISOString(),
    };
    await atomicWriteJsonFile(filePath, next);
    return next;
}
/**
 * 获取 Agent 初始化根目录
 *
 * @param agentId - Agent ID
 * @returns 初始化根目录路径
 */
export function getAgentInitRoot(agentId) {
    return path.join(getRuntimeHomeDir(), '.aws-bridge', 'instances', String(agentId));
}
