"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");
class Ssh extends core_1.Command {
    async run() {
        const { args } = await this.parse(Ssh);
        const spinner = (0, ora_1.default)('Connecting to cluster...').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);
            // Get cluster
            const cluster = await observabilityService.getObservabilityCluster();
            if (!cluster) {
                spinner.fail('No observability cluster found');
                console.log(chalk_1.default.yellow('\n⚠️  No observability cluster exists.\n'));
                console.log(chalk_1.default.dim('Create one with:'));
                console.log(`   ${chalk_1.default.cyan('flui env create')}\n`);
                return;
            }
            // Get node IP
            let nodeIp;
            let nodeName;
            if (args.node === 'master') {
                nodeIp = cluster.masterIpAddress;
                nodeName = 'Master Node';
            }
            else {
                // Find worker node
                const workerIndex = Number.parseInt(args.node.replace('worker-', ''));
                if (Number.isNaN(workerIndex)) {
                    spinner.fail('Invalid node name');
                    console.log(chalk_1.default.red(`\n❌ Invalid node name: ${args.node}\n`));
                    console.log(chalk_1.default.dim('Valid options: master, worker-1, worker-2, etc.\n'));
                    return;
                }
                const workerNode = cluster.nodes?.find((n) => n.nodeType === 'worker' &&
                    n.serverName.includes(`worker-${workerIndex}`));
                if (!workerNode) {
                    spinner.fail('Worker node not found');
                    console.log(chalk_1.default.red(`\n❌ Worker node ${args.node} not found\n`));
                    return;
                }
                nodeIp = workerNode.ipAddress;
                nodeName = `Worker Node ${workerIndex}`;
            }
            if (!nodeIp) {
                spinner.fail('Node IP not available');
                console.log(chalk_1.default.red(`\n❌ Node ${args.node} does not have an IP address yet\n`));
                console.log(chalk_1.default.dim('The node may still be provisioning. Check status with:'));
                console.log(`   ${chalk_1.default.cyan('flui env status')}\n`);
                return;
            }
            spinner.succeed(`Connecting to ${nodeName}...`);
            console.log(chalk_1.default.dim(`   SSH: root@${nodeIp}`));
            const exitHint = process.platform === 'win32'
                ? chalk_1.default.dim(`   Type ${chalk_1.default.white('exit')} to disconnect\n`)
                : chalk_1.default.dim(`   Type ${chalk_1.default.white('exit')} or press ${chalk_1.default.white('Ctrl+D')} to disconnect\n`);
            console.log(exitHint);
            // SSH into the node
            await sshService.sshConnect(nodeIp, 'root');
        }
        catch (error) {
            const message = error instanceof Error ? error.message : String(error);
            spinner.fail('SSH connection failed');
            console.log(chalk_1.default.red(`\n❌ ${message}\n`));
            this.exit(1);
        }
        finally {
            await (0, nest_app_1.closeNestApp)();
        }
    }
}
Ssh.description = 'SSH into a cluster node';
Ssh.examples = [
    '<%= config.bin %> <%= command.id %> master',
    '<%= config.bin %> <%= command.id %> worker-1',
    '<%= config.bin %> <%= command.id %> worker-2',
];
Ssh.args = {
    node: core_1.Args.string({
        description: 'Node to SSH into (master, worker-1, worker-2, etc.)',
        required: true,
    }),
};
exports.default = Ssh;
