"use strict";
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 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 cli_cluster_repository_1 = require("../../lib/repositories/cli-cluster.repository");
const encryption_service_1 = require("../../../../src/modules/shared/encryption/services/encryption.service");
const cluster_entity_1 = require("../../../../src/modules/infrastructure/clusters/entities/cluster.entity");
const context_banner_1 = require("../../lib/context-banner");
class EnvRefreshKubeconfig extends core_1.Command {
    async run() {
        (0, context_banner_1.printContextBanner)();
        const spinner = (0, ora_1.default)('Fetching kubeconfig from K3s master...').start();
        try {
            const app = await (0, nest_app_1.getNestApp)();
            const observabilityService = app.get(cli_observability_cluster_service_1.CliObservabilityClusterService);
            const sshService = app.get(cli_ssh_service_1.CliSshService);
            const clusterRepo = app.get(cli_cluster_repository_1.CliClusterRepository);
            const encryptionService = app.get(encryption_service_1.EncryptionService);
            const cluster = await observabilityService.getObservabilityCluster();
            if (!cluster) {
                spinner.fail('No observability cluster found');
                return;
            }
            if (cluster.status !== cluster_entity_1.ClusterStatus.READY) {
                spinner.fail(`Cluster is not ready (status: ${cluster.status})`);
                return;
            }
            const masterIp = cluster.masterIpAddress;
            if (!masterIp) {
                spinner.fail('Master IP address not available');
                return;
            }
            // Fetch real kubeconfig from K3s master
            const raw = await sshService.sshExec(masterIp, 'sudo cat /etc/rancher/k3s/k3s.yaml');
            // Replace localhost with real master IP
            const kubeconfig = raw.replaceAll('127.0.0.1', masterIp);
            // Encrypt and save
            cluster.kubeconfigEncrypted = encryptionService.encrypt(kubeconfig);
            await clusterRepo.save(cluster);
            spinner.succeed('Kubeconfig refreshed from K3s master');
            console.log(chalk_1.default.green(`\n  Cluster: ${cluster.name} (${cluster.id})`));
            console.log(chalk_1.default.green(`  Master:  ${masterIp}`));
            console.log(chalk_1.default.green(`  Size:    ${kubeconfig.length} bytes`));
            console.log(chalk_1.default.dim('\n  The kubeconfig now uses real K3s admin certificates.'));
        }
        catch (error) {
            spinner.fail('Failed to refresh kubeconfig');
            console.error(chalk_1.default.red(`\n  ${error.message}\n`));
            this.exit(1);
        }
        finally {
            await (0, nest_app_1.closeNestApp)();
        }
    }
}
EnvRefreshKubeconfig.description = 'Refresh kubeconfig by fetching the real one from the K3s master via SSH.\n' +
    'This replaces the locally generated kubeconfig with the actual /etc/rancher/k3s/k3s.yaml.';
EnvRefreshKubeconfig.examples = ['<%= config.bin %> <%= command.id %>'];
exports.default = EnvRefreshKubeconfig;
