"use strict";
/**
 * Remove Command Handler
 *
 * Removes a saved profile and its instance directory.
 */
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.handleRemove = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const ui_1 = require("../../utils/ui");
const prompt_1 = require("../../utils/prompt");
const errors_1 = require("../../errors");
const exit_codes_1 = require("../../errors/exit-codes");
const types_1 = require("./types");
const config_loader_facade_1 = require("../../config/config-loader-facade");
/**
 * Handle the remove command
 */
async function handleRemove(ctx, args) {
    await (0, ui_1.initUI)();
    const parsed = (0, types_1.parseArgs)(args);
    const { profileName, yes } = parsed;
    (0, types_1.rejectUnsupportedAuthOptions)(parsed, {
        usage: 'ccs auth remove <profile> [--yes]',
    });
    if (!profileName) {
        console.log((0, ui_1.fail)('Profile name is required'));
        console.log('');
        console.log(`Usage: ${(0, ui_1.color)('ccs auth remove <profile> [--yes]', 'command')}`);
        (0, errors_1.exitWithError)('Profile name is required', exit_codes_1.ExitCode.PROFILE_ERROR);
    }
    // Check existence in both legacy and unified
    const existsLegacy = ctx.registry.hasProfile(profileName);
    const existsUnified = ctx.registry.hasAccountUnified(profileName);
    if (!existsLegacy && !existsUnified) {
        console.log((0, ui_1.fail)(`Profile not found: ${profileName}`));
        (0, errors_1.exitWithError)(`Profile not found: ${profileName}`, exit_codes_1.ExitCode.PROFILE_ERROR);
    }
    try {
        // Get instance path and session count for impact display
        const instancePath = ctx.instanceMgr.getInstancePath(profileName);
        let sessionCount = 0;
        try {
            const sessionsDir = path.join(instancePath, 'session-env');
            if (fs.existsSync(sessionsDir)) {
                const files = fs.readdirSync(sessionsDir);
                sessionCount = files.filter((f) => f.endsWith('.json')).length;
            }
        }
        catch (_e) {
            // Ignore errors counting sessions
        }
        // Display impact
        console.log('');
        console.log(`Profile '${(0, ui_1.color)(profileName, 'command')}' will be permanently deleted.`);
        console.log(`  Instance path: ${instancePath}`);
        console.log(`  Sessions: ${sessionCount} conversation${sessionCount !== 1 ? 's' : ''}`);
        console.log('');
        // Interactive confirmation (or --yes flag)
        const confirmed = yes || (await prompt_1.InteractivePrompt.confirm('Delete this profile?', { default: false })); // Default to NO (safe)
        if (!confirmed) {
            console.log((0, ui_1.info)('Cancelled'));
            process.exit(0);
        }
        // Delete instance
        await ctx.instanceMgr.deleteInstance(profileName);
        // Delete profile from appropriate config
        if ((0, config_loader_facade_1.isUnifiedMode)() && existsUnified) {
            ctx.registry.removeAccountUnified(profileName);
        }
        if (existsLegacy) {
            ctx.registry.deleteProfile(profileName);
        }
        console.log((0, ui_1.ok)(`Profile removed: ${profileName}`));
        console.log('');
    }
    catch (error) {
        (0, errors_1.exitWithError)(`Failed to remove profile: ${error.message}`, exit_codes_1.ExitCode.GENERAL_ERROR);
    }
}
exports.handleRemove = handleRemove;
//# sourceMappingURL=remove-command.js.map