"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 () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("@oclif/core");
const chalk_1 = __importDefault(require("chalk"));
const ora_1 = __importDefault(require("ora"));
const fs = __importStar(require("node:fs/promises"));
const path = __importStar(require("node:path"));
const os = __importStar(require("node:os"));
const nest_app_1 = require("../../lib/nest-app");
const cli_observability_cluster_service_1 = require("../../services/cli-observability-cluster.service");
const cli_ssh_service_1 = require("../../services/cli-ssh.service");
const context_banner_1 = require("../../lib/context-banner");
class EnvRepairSshCa extends core_1.Command {
    async run() {
        const { flags } = await this.parse(EnvRepairSshCa);
        (0, context_banner_1.printContextBanner)();
        const profile = flags.profile ?? process.env.FLUI_PROFILE ?? this.readActiveProfile();
        const caKeyPath = path.join(os.homedir(), '.flui', 'profiles', profile, 'ca', 'ca_key');
        const spinner = (0, ora_1.default)('Reading local CA private key...').start();
        let caPrivateKey;
        try {
            caPrivateKey = (await fs.readFile(caKeyPath, 'utf-8')).trimEnd() + '\n';
            if (!caPrivateKey.includes('PRIVATE KEY')) {
                spinner.fail('CA private key file does not look like an OpenSSH key');
                this.exit(1);
                return;
            }
            spinner.succeed(`CA private key loaded from ${chalk_1.default.dim(caKeyPath)} (${caPrivateKey.length} bytes)`);
        }
        catch (err) {
            spinner.fail(`Could not read CA private key at ${caKeyPath}: ${err.message}`);
            this.log(chalk_1.default.yellow('\n  Hint: this profile may have never been initialized with a CA, or the path is wrong.'));
            this.exit(1);
            return;
        }
        const app = await (0, nest_app_1.getNestApp)();
        try {
            const obs = app.get(cli_observability_cluster_service_1.CliObservabilityClusterService);
            const ssh = app.get(cli_ssh_service_1.CliSshService);
            const cluster = await obs.getObservabilityCluster();
            if (!cluster?.masterIpAddress) {
                this.log(chalk_1.default.red('  No observability cluster found in this profile.'));
                this.exit(1);
                return;
            }
            const patchSpinner = (0, ora_1.default)(`Patching flui-secrets on ${cluster.masterIpAddress}...`).start();
            const base64 = Buffer.from(caPrivateKey).toString('base64');
            const patchCmd = `kubectl -n flui-system patch secret flui-secrets ` +
                `--type='json' -p='[{"op":"replace","path":"/data/SSH_CA_PRIVATE_KEY","value":"${base64}"}]'`;
            try {
                await ssh.sshExec(cluster.masterIpAddress, patchCmd);
                patchSpinner.succeed('Secret SSH_CA_PRIVATE_KEY patched');
            }
            catch (err) {
                patchSpinner.fail(`Patch failed: ${err.message}`);
                this.exit(1);
                return;
            }
            if (!flags['no-restart']) {
                const restartSpinner = (0, ora_1.default)('Restarting flui-api...').start();
                try {
                    await ssh.sshExec(cluster.masterIpAddress, 'kubectl -n flui-system rollout restart deployment/flui-api');
                    restartSpinner.succeed('flui-api rolling restart triggered');
                }
                catch (err) {
                    restartSpinner.warn(`Restart failed (Secret was patched OK): ${err.message}`);
                }
            }
            this.log('');
            this.log(chalk_1.default.green('  ✅ CA repair complete. Dashboard terminal should now work.'));
            this.log(chalk_1.default.dim('     Hard-refresh the dashboard if it was already open.\n'));
        }
        finally {
            await (0, nest_app_1.closeNestApp)();
        }
    }
    readActiveProfile() {
        try {
            const contextFile = path.join(os.homedir(), '.flui', 'context');
            const fsSync = require('node:fs');
            return fsSync.readFileSync(contextFile, 'utf-8').trim() || 'default';
        }
        catch {
            return 'default';
        }
    }
}
EnvRepairSshCa.description = 'Backfill the SSH CA private key into the cluster flui-secrets Secret. Used to repair clusters that were provisioned before the CA seeding flow was complete — symptom is the Dashboard SSH terminal failing with "CA private key not available". Reads the CA private key from the active profile (~/.flui/profiles/<profile>/ca/ca_key) and patches the in-cluster Secret over SSH+cert.';
EnvRepairSshCa.examples = [
    '<%= config.bin %> <%= command.id %>',
    '<%= config.bin %> <%= command.id %> --no-restart',
];
EnvRepairSshCa.flags = {
    'no-restart': core_1.Flags.boolean({
        description: 'Skip the flui-api rolling restart after patching the Secret',
    }),
    profile: core_1.Flags.string({
        description: 'Active profile name (default: $FLUI_PROFILE or contents of ~/.flui/context, fallback "default")',
    }),
};
exports.default = EnvRepairSshCa;
