#!/usr/bin/env node
"use strict";
/**
 * Manages delegation session persistence for multi-turn conversations
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SessionManager = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const config_loader_facade_1 = require("../config/config-loader-facade");
/**
 * Session Manager Class
 */
class SessionManager {
    constructor() {
        this.sessionsPath = path.join((0, config_loader_facade_1.getCcsDir)(), 'delegation-sessions.json');
    }
    /**
     * Store new session metadata
     */
    storeSession(profile, sessionData) {
        const sessions = this.loadSessions();
        const key = `${profile}:latest`;
        sessions[key] = {
            sessionId: sessionData.sessionId,
            profile,
            startTime: Date.now(),
            lastTurnTime: Date.now(),
            totalCost: sessionData.totalCost || 0,
            turns: 1,
            cwd: sessionData.cwd || process.cwd(),
        };
        this.saveSessions(sessions);
        if (process.env.CCS_DEBUG) {
            console.error(`[i] Stored session: ${sessionData.sessionId} for ${profile}`);
        }
    }
    /**
     * Update session after additional turn
     */
    updateSession(profile, sessionId, turnData) {
        const sessions = this.loadSessions();
        const key = `${profile}:latest`;
        if (sessions[key]?.sessionId === sessionId) {
            sessions[key].lastTurnTime = Date.now();
            sessions[key].totalCost += turnData.totalCost || 0;
            sessions[key].turns += 1;
            this.saveSessions(sessions);
            if (process.env.CCS_DEBUG) {
                const cost = sessions[key].totalCost !== undefined && sessions[key].totalCost !== null
                    ? sessions[key].totalCost.toFixed(4)
                    : '0.0000';
                console.error(`[i] Updated session: ${sessionId}, total: $${cost}, turns: ${sessions[key].turns}`);
            }
        }
    }
    /**
     * Get last session for profile
     */
    getLastSession(profile) {
        const sessions = this.loadSessions();
        const key = `${profile}:latest`;
        return sessions[key] || null;
    }
    /**
     * Clear all sessions for profile
     */
    clearProfile(profile) {
        const sessions = this.loadSessions();
        const key = `${profile}:latest`;
        delete sessions[key];
        this.saveSessions(sessions);
    }
    /**
     * Clean up expired sessions (>30 days)
     */
    cleanupExpired() {
        const sessions = this.loadSessions();
        const now = Date.now();
        const maxAge = 30 * 24 * 60 * 60 * 1000; // 30 days
        let cleaned = 0;
        Object.keys(sessions).forEach((key) => {
            if (now - sessions[key].lastTurnTime > maxAge) {
                delete sessions[key];
                cleaned++;
            }
        });
        if (cleaned > 0) {
            this.saveSessions(sessions);
            if (process.env.CCS_DEBUG) {
                console.error(`[i] Cleaned ${cleaned} expired sessions`);
            }
        }
    }
    /**
     * Load sessions from disk
     */
    loadSessions() {
        try {
            if (!fs.existsSync(this.sessionsPath)) {
                return {};
            }
            const content = fs.readFileSync(this.sessionsPath, 'utf8');
            return JSON.parse(content);
        }
        catch (error) {
            if (process.env.CCS_DEBUG) {
                console.warn(`[!] Failed to load sessions: ${error.message}`);
            }
            return {};
        }
    }
    /**
     * Save sessions to disk
     */
    saveSessions(sessions) {
        try {
            const dir = path.dirname(this.sessionsPath);
            if (!fs.existsSync(dir)) {
                fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
            }
            fs.writeFileSync(this.sessionsPath, JSON.stringify(sessions, null, 2), { mode: 0o600 });
        }
        catch (error) {
            console.error(`[!] Failed to save sessions: ${error.message}`);
        }
    }
}
exports.SessionManager = SessionManager;
//# sourceMappingURL=session-manager.js.map