"use strict";
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.handleFinalizeKeyRotation = void 0;
const fs = __importStar(require("fs"));
const docker_1 = require("../../docker");
const config_generator_1 = require("../../cliproxy/config/config-generator");
const port_manager_1 = require("../../cliproxy/config/port-manager");
const docker_key_rotation_1 = require("../../docker/docker-key-rotation");
const ui_1 = require("../../utils/ui");
const options_1 = require("./options");
const KNOWN_FLAGS = ['--host', '--container-scope'];
function shouldWriteContainerVolume(args) {
    return args.includes('--container-scope') || fs.existsSync('/.dockerenv');
}
async function handleFinalizeKeyRotation(args) {
    await (0, ui_1.initUI)();
    const parsed = (0, options_1.parseDockerTarget)(args, KNOWN_FLAGS);
    const remainingArgs = parsed.remainingArgs.filter((arg) => arg !== '--container-scope');
    const errors = [
        ...parsed.errors,
        ...(0, options_1.collectUnexpectedDockerArgs)(remainingArgs, {
            knownFlags: [],
            maxPositionals: 0,
        }),
    ];
    if (errors.length > 0) {
        console.error((0, ui_1.box)((0, ui_1.fail)(errors.join('\n')), { title: 'Docker', padding: 1 }));
        process.exitCode = 1;
        return;
    }
    if (!shouldWriteContainerVolume(args)) {
        try {
            const output = new docker_1.DockerExecutor().finalizeKeyRotation({ host: parsed.host });
            if (output.trim()) {
                console.log(output.trim());
            }
        }
        catch (error) {
            console.error((0, ui_1.box)((0, ui_1.fail)(error instanceof Error ? error.message : String(error)), {
                title: 'Docker',
                padding: 1,
            }));
            process.exitCode = 1;
        }
        return;
    }
    const status = (0, docker_key_rotation_1.finalizeDockerKeyRotation)();
    if ((0, config_generator_1.configExists)(port_manager_1.CLIPROXY_DEFAULT_PORT)) {
        (0, config_generator_1.regenerateConfig)(port_manager_1.CLIPROXY_DEFAULT_PORT);
    }
    console.log((0, ui_1.ok)('Docker CLIProxy legacy API key grace period finalized.'));
    console.log((0, ui_1.info)(`Current API key: ${status.maskedApiKey ?? '(not configured)'}`));
    console.log((0, ui_1.info)('Restart CLIProxy if it is already running to reload the regenerated config.'));
}
exports.handleFinalizeKeyRotation = handleFinalizeKeyRotation;
//# sourceMappingURL=finalize-key-rotation-subcommand.js.map