"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.ensureDockerCliproxyAuth = void 0;
const crypto_1 = require("crypto");
const child_process_1 = require("child_process");
const fs = __importStar(require("fs"));
const binary_manager_1 = require("../cliproxy/binary-manager");
const config_generator_1 = require("../cliproxy/config/config-generator");
const port_manager_1 = require("../cliproxy/config/port-manager");
const path_resolver_1 = require("../cliproxy/config/path-resolver");
const session_tracker_1 = require("../cliproxy/session-tracker");
const config_loader_facade_1 = require("../config/config-loader-facade");
const docker_key_rotation_1 = require("./docker-key-rotation");
function generateDockerSecret() {
    return (0, crypto_1.randomBytes)(32).toString('base64url');
}
function ensureDockerCliproxyAuth() {
    const now = new Date();
    const hadUnifiedConfig = fs.existsSync((0, config_loader_facade_1.getConfigYamlPath)());
    const hadCliproxyConfig = (0, config_generator_1.configExists)(port_manager_1.CLIPROXY_DEFAULT_PORT);
    const cliproxyConfigPath = (0, path_resolver_1.getCliproxyConfigPath)();
    const existingCliproxyConfig = hadCliproxyConfig
        ? fs.readFileSync(cliproxyConfigPath, 'utf8')
        : '';
    const config = (0, config_loader_facade_1.loadOrCreateUnifiedConfig)();
    const auth = config.cliproxy.auth;
    const needsApiKey = !auth?.api_key || auth.api_key === config_generator_1.CCS_INTERNAL_API_KEY;
    const needsManagementSecret = !auth?.management_secret || auth.management_secret === config_generator_1.CCS_CONTROL_PANEL_SECRET;
    const stateRead = (0, docker_key_rotation_1.readDockerBootstrapState)();
    const existingState = stateRead.state;
    const existingApiKey = auth?.api_key;
    let replacementApiKey = existingApiKey;
    let configChanged = false;
    if (needsApiKey || needsManagementSecret) {
        (0, config_loader_facade_1.mutateConfig)((nextConfig) => {
            var _a;
            (_a = nextConfig.cliproxy).auth ?? (_a.auth = {});
            if (needsApiKey) {
                replacementApiKey = generateDockerSecret();
                nextConfig.cliproxy.auth.api_key = replacementApiKey;
            }
            if (needsManagementSecret) {
                nextConfig.cliproxy.auth.management_secret = generateDockerSecret();
            }
        });
        configChanged = true;
    }
    if (!replacementApiKey) {
        replacementApiKey = (0, config_loader_facade_1.loadOrCreateUnifiedConfig)().cliproxy.auth?.api_key;
    }
    const existingLegacyKeyInCliproxyConfig = existingCliproxyConfig.includes(`"${docker_key_rotation_1.DOCKER_LEGACY_API_KEY}"`);
    const freshInstall = !hadUnifiedConfig && !hadCliproxyConfig;
    const oldDefaultUpgrade = needsApiKey && !freshInstall;
    const explicitLegacyRestore = (0, docker_key_rotation_1.shouldRestoreDockerLegacyApiKey)();
    const legacyRestoreEligible = !existingState?.legacyKeyGrace;
    const alreadyBrokenUpgrade = explicitLegacyRestore &&
        legacyRestoreEligible &&
        hadCliproxyConfig &&
        (0, docker_key_rotation_1.isLikelyDockerGeneratedApiKey)(replacementApiKey) &&
        !existingLegacyKeyInCliproxyConfig;
    const corruptedRecoverableUpgrade = explicitLegacyRestore &&
        stateRead.corrupted &&
        hadCliproxyConfig &&
        (0, docker_key_rotation_1.isLikelyDockerGeneratedApiKey)(replacementApiKey);
    let nextState = existingState ?? (0, docker_key_rotation_1.createDockerBootstrapState)(replacementApiKey, now);
    if (replacementApiKey && !nextState.apiKey) {
        nextState = { ...nextState, apiKey: replacementApiKey };
    }
    if (replacementApiKey &&
        !(0, docker_key_rotation_1.isDockerLegacyKeyGraceActive)(existingState, now) &&
        (oldDefaultUpgrade || alreadyBrokenUpgrade || corruptedRecoverableUpgrade)) {
        nextState = (0, docker_key_rotation_1.addLegacyKeyGrace)(nextState, replacementApiKey, now);
    }
    if (!existingState || stateRead.corrupted || nextState !== existingState) {
        (0, docker_key_rotation_1.writeDockerBootstrapState)(nextState);
    }
    const legacyShouldBePresent = (0, docker_key_rotation_1.isDockerLegacyKeyGraceActive)(nextState, now);
    const legacyPresenceChanged = existingLegacyKeyInCliproxyConfig !== legacyShouldBePresent;
    return configChanged || legacyPresenceChanged;
}
exports.ensureDockerCliproxyAuth = ensureDockerCliproxyAuth;
async function prepareIntegratedRuntime() {
    const binaryPath = await (0, binary_manager_1.ensureCLIProxyBinary)(false);
    const authWasGenerated = ensureDockerCliproxyAuth();
    const configPath = !(0, config_generator_1.configExists)(port_manager_1.CLIPROXY_DEFAULT_PORT)
        ? (0, config_generator_1.generateConfig)('gemini', port_manager_1.CLIPROXY_DEFAULT_PORT)
        : authWasGenerated || (0, config_generator_1.configNeedsRegeneration)()
            ? (0, config_generator_1.regenerateConfig)(port_manager_1.CLIPROXY_DEFAULT_PORT)
            : (0, path_resolver_1.getCliproxyConfigPath)();
    return { binaryPath, configPath };
}
async function runCliproxy() {
    const { binaryPath, configPath } = await prepareIntegratedRuntime();
    return new Promise((resolve, reject) => {
        const child = (0, child_process_1.spawn)(binaryPath, ['--config', configPath], {
            stdio: 'inherit',
            env: {
                ...process.env,
                WRITABLE_PATH: (0, config_generator_1.getCliproxyWritablePath)(),
            },
        });
        // Register session lock so dashboard can detect the running proxy
        let sessionId;
        child.on('spawn', () => {
            if (!child.pid)
                return;
            try {
                const version = (0, binary_manager_1.getInstalledCliproxyVersion)();
                sessionId = (0, session_tracker_1.registerSession)(port_manager_1.CLIPROXY_DEFAULT_PORT, child.pid, version, 'plus');
            }
            catch (err) {
                console.error(`[cliproxy] Failed to register session lock: ${err instanceof Error ? err.message : String(err)}`);
            }
        });
        child.on('error', reject);
        child.on('close', (code) => {
            if (sessionId) {
                (0, session_tracker_1.unregisterSession)(sessionId, port_manager_1.CLIPROXY_DEFAULT_PORT);
            }
            resolve(code ?? 1);
        });
    });
}
async function main() {
    const command = process.argv[2];
    if (command !== 'run-cliproxy') {
        console.error('[X] Usage: node dist/docker/docker-bootstrap.js run-cliproxy');
        return 1;
    }
    return runCliproxy();
}
if (require.main === module) {
    void main()
        .then((exitCode) => {
        process.exitCode = exitCode;
    })
        .catch((error) => {
        console.error(`[X] Failed to prepare Docker runtime: ${error instanceof Error ? error.message : String(error)}`);
        process.exitCode = 1;
    });
}
//# sourceMappingURL=docker-bootstrap.js.map