import { readdir, unlink, rm } from 'fs/promises';
import { join } from 'path';
import { getMcpcHome, getBridgesDir, getLogsDir, fileExists, cleanupOrphanedLogFiles } from '../../lib/index.js';
import { formatOutput, formatSuccess, formatWarning } from '../output.js';
import { loadSessions, deleteSession, consolidateSessions } from '../../lib/sessions.js';
import { stopBridge } from '../../lib/bridge-manager.js';
import { createLogger } from '../../lib/logger.js';
import { deleteAuthProfiles } from '../../lib/auth/profiles.js';
const logger = createLogger('clean');
async function cleanStale() {
    const consolidateResult = await consolidateSessions(true);
    const orphanedBridgeLogs = await cleanupOrphanedLogFiles(consolidateResult.sessions);
    return {
        crashedBridges: consolidateResult.crashedBridges,
        expiredSessions: consolidateResult.expiredSessions,
        orphanedBridgeLogs,
    };
}
async function cleanSessions() {
    const sessionsStorage = await loadSessions();
    const sessionNames = Object.keys(sessionsStorage.sessions);
    let count = 0;
    for (const name of sessionNames) {
        try {
            try {
                await stopBridge(name);
            }
            catch {
            }
            await deleteSession(name);
            count++;
            logger.debug(`Cleaned session: ${name}`);
        }
        catch (error) {
            logger.warn(`Failed to clean session ${name}:`, error);
        }
    }
    return count;
}
async function cleanLogs() {
    const logsDir = getLogsDir();
    if (!(await fileExists(logsDir))) {
        return 0;
    }
    let count = 0;
    const files = await readdir(logsDir);
    for (const file of files) {
        if (file.endsWith('.log') || file.match(/\.log\.\d+$/)) {
            try {
                await unlink(join(logsDir, file));
                count++;
            }
            catch {
            }
        }
    }
    logger.debug(`Removed ${count} log files`);
    return count;
}
async function cleanAll() {
    const result = {
        crashedBridges: 0,
        expiredSessions: 0,
        orphanedBridgeLogs: 0,
        sessions: 0,
        profiles: 0,
        logs: 0,
    };
    result.sessions = await cleanSessions();
    const profilesResult = await deleteAuthProfiles();
    result.profiles = profilesResult.count;
    result.affectedSessions = profilesResult.affectedSessions;
    result.logs = await cleanLogs();
    const staleResult = await cleanStale();
    result.crashedBridges = staleResult.crashedBridges;
    result.expiredSessions = staleResult.expiredSessions;
    result.orphanedBridgeLogs = staleResult.orphanedBridgeLogs;
    const mcpcHome = getMcpcHome();
    const bridgesDir = getBridgesDir();
    const logsDir = getLogsDir();
    for (const dir of [bridgesDir, logsDir]) {
        if (await fileExists(dir)) {
            try {
                await rm(dir, { recursive: true, force: true });
            }
            catch {
            }
        }
    }
    if (await fileExists(mcpcHome)) {
        try {
            const files = await readdir(mcpcHome);
            if (files.length === 0) {
                await rm(mcpcHome, { recursive: true, force: true });
                logger.debug(`Removed empty ${mcpcHome}`);
            }
        }
        catch {
        }
    }
    return result;
}
export async function clean(options) {
    const result = {
        crashedBridges: 0,
        expiredSessions: 0,
        orphanedBridgeLogs: 0,
        sessions: 0,
        profiles: 0,
        logs: 0,
    };
    if (options.all) {
        const allResult = await cleanAll();
        if (options.outputMode === 'human') {
            const parts = [];
            if (allResult.sessions > 0)
                parts.push(`${allResult.sessions} session(s)`);
            if (allResult.profiles > 0)
                parts.push(`${allResult.profiles} profile(s)`);
            if (allResult.logs > 0)
                parts.push(`${allResult.logs} log file(s)`);
            if (parts.length > 0) {
                console.log(formatSuccess(`Cleaned ${parts.join(', ')}`));
            }
            else {
                console.log(formatSuccess('Nothing to clean'));
            }
        }
        else {
            console.log(formatOutput(allResult, 'json'));
        }
        return;
    }
    const cleaningSpecific = options.sessions || options.profiles || options.logs;
    if (!cleaningSpecific) {
        const staleResult = await cleanStale();
        result.crashedBridges = staleResult.crashedBridges;
        result.expiredSessions = staleResult.expiredSessions;
        result.orphanedBridgeLogs = staleResult.orphanedBridgeLogs;
    }
    if (options.sessions) {
        result.sessions = await cleanSessions();
    }
    if (options.profiles) {
        const profilesResult = await deleteAuthProfiles();
        result.profiles = profilesResult.count;
        result.affectedSessions = profilesResult.affectedSessions;
    }
    if (options.logs) {
        result.logs = await cleanLogs();
    }
    if (options.outputMode === 'human') {
        const messages = [];
        if (!cleaningSpecific) {
            const hasCleanups = result.crashedBridges > 0 ||
                result.expiredSessions > 0 ||
                result.orphanedBridgeLogs > 0;
            if (hasCleanups) {
                const parts = [];
                if (result.crashedBridges > 0)
                    parts.push(`${result.crashedBridges} crashed bridge(s)`);
                if (result.expiredSessions > 0)
                    parts.push(`${result.expiredSessions} expired session(s)`);
                if (result.orphanedBridgeLogs > 0)
                    parts.push(`${result.orphanedBridgeLogs} orphaned log(s)`);
                messages.push(`Cleaned ${parts.join(', ')}`);
            }
            else {
                messages.push('No stale resources found');
            }
        }
        if (options.sessions) {
            messages.push(`Removed ${result.sessions} session(s)`);
        }
        if (options.profiles) {
            messages.push(result.profiles > 0 ? `Removed ${result.profiles} authentication profile(s)` : 'No profiles to remove');
        }
        if (options.logs) {
            messages.push(`Removed ${result.logs} log file(s)`);
        }
        for (const msg of messages) {
            console.log(formatSuccess(msg));
        }
        if (result.affectedSessions && result.affectedSessions.length > 0) {
            console.log(formatWarning(`Warning: ${result.affectedSessions.length} session(s) were using deleted profiles: ${result.affectedSessions.join(', ')}`));
            console.log(formatWarning('These sessions may fail to authenticate. Recreate them or login again.'));
        }
    }
    else {
        console.log(formatOutput(result, 'json'));
    }
}
//# sourceMappingURL=clean.js.map