"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 context_banner_1 = require("../../lib/context-banner");
const cli_observability_cluster_service_1 = require("../../services/cli-observability-cluster.service");
const cluster_node_scaling_service_1 = require("../../../../src/modules/infrastructure/clusters/services/cluster-node-scaling.service");
const cluster_capacity_service_1 = require("../../../../src/modules/infrastructure/clusters/services/cluster-capacity.service");
const cli_node_repository_1 = require("../../lib/repositories/cli-node.repository");
const prompts_1 = require("../../lib/prompts");
class EnvScaleNode extends core_1.Command {
    async run() {
        const { args, flags } = await this.parse(EnvScaleNode);
        (0, context_banner_1.printContextBanner)();
        const spinner = (0, ora_1.default)('Preparing scale-node plan...').start();
        try {
            const app = await (0, nest_app_1.getNestApp)();
            const observabilityService = app.get(cli_observability_cluster_service_1.CliObservabilityClusterService);
            const nodeRepo = app.get(cli_node_repository_1.CliNodeRepository);
            const capacityService = app.get(cluster_capacity_service_1.ClusterCapacityService);
            const scalingService = app.get(cluster_node_scaling_service_1.ClusterNodeScalingService);
            const cluster = await observabilityService.getObservabilityCluster();
            if (!cluster) {
                spinner.fail('No observability cluster found');
                return;
            }
            const nodes = await nodeRepo.find({ where: { clusterId: cluster.id } });
            const target = nodes.find((n) => n.serverName === args.name);
            if (!target) {
                spinner.fail(`Node "${args.name}" not found`);
                return;
            }
            const [preview, plan] = await Promise.all([
                scalingService.previewScaleNode(cluster.id, target.id),
                capacityService.getPlan(cluster.id),
            ]);
            spinner.succeed('Plan computed');
            let targetType = flags.type;
            let cand = targetType
                ? plan.candidates.find((c) => c.name === targetType)
                : undefined;
            if (!targetType) {
                cand = plan.candidates.find((c) => c.direction === 'upgrade');
                if (!cand) {
                    console.log(chalk_1.default.red('\n❌ No upgrade candidate available. Pass --type explicitly.\n'));
                    this.exit(1);
                }
                targetType = cand.name;
                console.log(chalk_1.default.dim(`   (auto-selected next-bigger type: ${chalk_1.default.bold(targetType)})`));
            }
            console.log(chalk_1.default.cyan('\n🖥  Scale Node Plan\n'));
            console.log(`   ${chalk_1.default.bold('Node:')}        ${target.serverName}`);
            console.log(`   ${chalk_1.default.bold('From:')}        ${preview.node.currentServerType}`);
            console.log(`   ${chalk_1.default.bold('To:')}          ${targetType}`);
            if (cand) {
                let deltaStr;
                if (cand.monthlyDeltaEur === 'n/a')
                    deltaStr = 'n/a';
                else {
                    const sign = Number.parseFloat(cand.monthlyDeltaEur) > 0 ? '+' : '';
                    deltaStr = sign + cand.monthlyDeltaEur;
                }
                console.log(`   ${chalk_1.default.bold('Cost/month:')}  €${cand.monthlyCostEur} (${deltaStr} delta)`);
            }
            console.log(`   ${chalk_1.default.bold('Downtime:')}    ~${Math.round(preview.expectedDowntimeMs / 60000)} min`);
            if (preview.affectedDedicatedApps.length > 0) {
                console.log(chalk_1.default.yellow(`\n   ⚠️  Hosts ${preview.affectedDedicatedApps.length} dedicated workload(s):`));
                for (const app of preview.affectedDedicatedApps) {
                    console.log(chalk_1.default.yellow(`     • ${app.slug}`));
                }
            }
            if (!flags.confirm) {
                console.log('');
                console.log(chalk_1.default.yellow(`   To confirm, type the node name exactly: ${chalk_1.default.bold(target.serverName)}`));
                const ok = await (0, prompts_1.confirmByTypingPrompt)(chalk_1.default.yellow('⚠️  Node name'), target.serverName);
                if (!ok) {
                    console.log(chalk_1.default.green('\n✅ Cancelled\n'));
                    return;
                }
            }
            const run = (0, ora_1.default)({
                text: `Scaling ${target.serverName} to ${targetType}...`,
                color: 'yellow',
            }).start();
            try {
                const op = await scalingService.scaleNode(cluster.id, target.id, {
                    targetServerType: targetType,
                    upgradeDisk: flags.upgradeDisk,
                });
                run.succeed(`Node scaled. Operation ${op.id} → ${op.status}`);
            }
            catch (error) {
                run.fail('Scale-node failed');
                throw error;
            }
            console.log('');
        }
        catch (error) {
            console.log(chalk_1.default.red('\n❌ Error:\n'));
            console.log(`   ${error instanceof Error ? error.message : String(error)}\n`);
            this.exit(1);
        }
        finally {
            await (0, nest_app_1.closeNestApp)();
        }
    }
}
EnvScaleNode.description = 'Vertically scale a worker node to a new server type. Planned-maintenance operation. ' +
    'For the master, use `flui env scale-master` instead.';
EnvScaleNode.examples = [
    '<%= config.bin %> <%= command.id %> worker-1 --type cx32',
    '<%= config.bin %> <%= command.id %> worker-1 --type PRO2-S --confirm',
];
EnvScaleNode.args = {
    name: core_1.Args.string({
        description: 'Worker node name (e.g. flui-cluster-worker-1)',
        required: true,
    }),
};
EnvScaleNode.flags = {
    type: core_1.Flags.string({
        char: 't',
        description: 'Target provider server type name. If omitted, auto-picks the next-bigger upgrade candidate (smallest +€/month delta).',
    }),
    upgradeDisk: core_1.Flags.boolean({
        description: '[Hetzner] Also grow the local OS disk (one-way).',
        default: false,
    }),
    confirm: core_1.Flags.boolean({
        description: 'Skip the typed confirmation prompt',
        default: false,
    }),
};
exports.default = EnvScaleNode;
