import fs from 'fs/promises';
import path from 'path';
export class TerminalSessionManager {
    constructor(logger) {
        this.logger = logger;
        this.configDir = path.join(process.cwd(), 'data');
        this.configPath = path.join(this.configDir, 'terminal-sessions.json');
        this.config = {
            sessions: [],
            lastUpdated: new Date().toISOString()
        };
    }
    async initialize() {
        try {
            await this.ensureConfigDirectory();
            await this.loadConfig();
            this.logger.info('终端会话管理器初始化完成');
        }
        catch (error) {
            this.logger.error('终端会话管理器初始化失败:', error);
            throw error;
        }
    }
    async ensureConfigDirectory() {
        try {
            await fs.access(this.configDir);
        }
        catch {
            await fs.mkdir(this.configDir, { recursive: true });
            this.logger.info(`创建配置目录: ${this.configDir}`);
        }
    }
    async loadConfig() {
        try {
            const data = await fs.readFile(this.configPath, 'utf-8');
            this.config = JSON.parse(data);
            this.logger.info('终端会话配置加载成功');
        }
        catch (error) {
            if (error.code === 'ENOENT') {
                this.logger.info('终端会话配置文件不存在，使用默认配置');
                await this.saveConfig();
            }
            else {
                this.logger.error('加载终端会话配置失败:', error);
                throw error;
            }
        }
    }
    async saveConfig() {
        try {
            this.config.lastUpdated = new Date().toISOString();
            await fs.writeFile(this.configPath, JSON.stringify(this.config, null, 2), 'utf-8');
            this.logger.debug('终端会话配置保存成功');
        }
        catch (error) {
            this.logger.error('保存终端会话配置失败:', error);
            throw error;
        }
    }
    async saveSession(sessionData) {
        try {
            const persistedSession = {
                id: sessionData.id,
                name: sessionData.name,
                workingDirectory: sessionData.workingDirectory,
                createdAt: sessionData.createdAt.toISOString(),
                lastActivity: sessionData.lastActivity.toISOString(),
                isActive: sessionData.isActive
            };
            const existingIndex = this.config.sessions.findIndex(s => s.id === sessionData.id);
            if (existingIndex >= 0) {
                this.config.sessions[existingIndex] = persistedSession;
                this.logger.debug(`更新终端会话: ${sessionData.id} - ${sessionData.name}`);
            }
            else {
                this.config.sessions.push(persistedSession);
                this.logger.debug(`保存新终端会话: ${sessionData.id} - ${sessionData.name}`);
            }
            await this.saveConfig();
        }
        catch (error) {
            this.logger.error('保存终端会话失败:', error);
            throw error;
        }
    }
    async updateSessionName(sessionId, newName) {
        try {
            const session = this.config.sessions.find(s => s.id === sessionId);
            if (session) {
                session.name = newName;
                session.lastActivity = new Date().toISOString();
                await this.saveConfig();
                this.logger.info(`更新终端会话名称: ${sessionId} -> ${newName}`);
            }
            else {
                this.logger.warn(`尝试更新不存在的会话名称: ${sessionId}`);
            }
        }
        catch (error) {
            this.logger.error('更新会话名称失败:', error);
            throw error;
        }
    }
    async removeSession(sessionId) {
        try {
            const initialLength = this.config.sessions.length;
            this.config.sessions = this.config.sessions.filter(s => s.id !== sessionId);
            if (this.config.sessions.length < initialLength) {
                await this.saveConfig();
                this.logger.info(`删除终端会话: ${sessionId}`);
            }
            else {
                this.logger.debug(`尝试删除不存在的会话: ${sessionId}`);
            }
        }
        catch (error) {
            this.logger.error('删除会话失败:', error);
            throw error;
        }
    }
    getSavedSessions() {
        return [...this.config.sessions];
    }
    getSession(sessionId) {
        return this.config.sessions.find(s => s.id === sessionId);
    }
    async cleanupExpiredSessions() {
        try {
            const now = new Date();
            const expirationThreshold = 7 * 24 * 60 * 60 * 1000;
            const initialLength = this.config.sessions.length;
            this.config.sessions = this.config.sessions.filter(session => {
                const lastActivity = new Date(session.lastActivity);
                const timeDiff = now.getTime() - lastActivity.getTime();
                return timeDiff < expirationThreshold;
            });
            const removedCount = initialLength - this.config.sessions.length;
            if (removedCount > 0) {
                await this.saveConfig();
                this.logger.info(`清理了 ${removedCount} 个过期的终端会话`);
            }
        }
        catch (error) {
            this.logger.error('清理过期会话失败:', error);
        }
    }
    async setSessionActive(sessionId, isActive) {
        try {
            const session = this.config.sessions.find(s => s.id === sessionId);
            if (session) {
                session.isActive = isActive;
                session.lastActivity = new Date().toISOString();
                await this.saveConfig();
                this.logger.debug(`设置会话活动状态: ${sessionId} -> ${isActive}`);
            }
        }
        catch (error) {
            this.logger.error('设置会话活动状态失败:', error);
            throw error;
        }
    }
    getConfigPath() {
        return this.configPath;
    }
}
