"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 cli_app_service_1 = require("../../lib/services/cli-app.service");
const resolve_cluster_1 = require("../../lib/resolve-cluster");
class AppStatus extends core_1.Command {
    async run() {
        const { args, flags } = await this.parse(AppStatus);
        const spinner = (0, ora_1.default)(`Fetching status for "${args.name}"...`).start();
        try {
            const { id: clusterId } = await (0, resolve_cluster_1.resolveCluster)(flags.cluster);
            const service = await cli_app_service_1.CliAppService.create(clusterId);
            const app = await service.getAppByName(args.name);
            const runtime = await service.getRuntime(app.id);
            spinner.stop();
            if (flags.output === 'json') {
                console.log(JSON.stringify({ app, runtime }, null, 2));
                return;
            }
            console.log(chalk_1.default.cyan(`\n  ${app.name}\n`));
            console.log(`  ${chalk_1.default.bold('ID:')}         ${app.id}`);
            console.log(`  ${chalk_1.default.bold('Status:')}     ${this.colorStatus(app.status)}`);
            console.log(`  ${chalk_1.default.bold('Kind:')}       ${(app.kind || '').toLowerCase()}`);
            console.log(`  ${chalk_1.default.bold('Exposure:')}   ${(app.exposure || '').toLowerCase()}`);
            if (app.lastDeployedAt) {
                console.log(`  ${chalk_1.default.bold('Deployed:')}   ${new Date(app.lastDeployedAt).toLocaleString()}`);
            }
            console.log(chalk_1.default.cyan('\n  Replicas\n'));
            const r = runtime.replicas;
            const ready = r.ready ?? 0;
            const desired = r.desired ?? 0;
            const replicaColor = ready === desired && desired > 0 ? chalk_1.default.green : chalk_1.default.yellow;
            console.log(`  ${chalk_1.default.bold('Desired:')}    ${desired}`);
            console.log(`  ${chalk_1.default.bold('Ready:')}      ${replicaColor(String(ready))}`);
            if (r.unavailable) {
                console.log(`  ${chalk_1.default.bold('Unavailable:')} ${chalk_1.default.red(String(r.unavailable))}`);
            }
            if (runtime.containers.length > 0) {
                console.log(chalk_1.default.cyan('\n  Containers\n'));
                for (const c of runtime.containers)
                    this.printContainer(c);
            }
            console.log('');
        }
        catch (error) {
            spinner.fail('Failed to fetch status');
            console.log(chalk_1.default.red(`\n  Error: ${error.message}\n`));
            this.exit(1);
        }
    }
    printContainer(c) {
        console.log(`  ${chalk_1.default.bold(c.name)}`);
        console.log(`    ${chalk_1.default.dim('image:')}   ${c.image}`);
        const req = c.requests;
        const lim = c.limits;
        if (req.cpu || req.memory) {
            console.log(`    ${chalk_1.default.dim('requests:')} cpu=${req.cpu ?? '-'}  mem=${req.memory ?? '-'}`);
        }
        if (lim.cpu || lim.memory) {
            console.log(`    ${chalk_1.default.dim('limits:')}   cpu=${lim.cpu ?? '-'}  mem=${lim.memory ?? '-'}`);
        }
        if (c.usage) {
            const u = c.usage;
            console.log(`    ${chalk_1.default.dim('usage:')}    cpu=${u.cpu ?? '-'}  mem=${u.memory ?? '-'}`);
        }
    }
    colorStatus(status) {
        const s = status.toLowerCase();
        if (s === 'running')
            return chalk_1.default.green(status);
        if (s === 'stopped')
            return chalk_1.default.yellow(status);
        if (s === 'failed' || s === 'degraded')
            return chalk_1.default.red(status);
        if (s === 'provisioning' || s === 'updating')
            return chalk_1.default.blue(status);
        return chalk_1.default.dim(status);
    }
}
AppStatus.description = 'Show live runtime status of an application';
AppStatus.examples = [
    '<%= config.bin %> <%= command.id %> my-api',
    '<%= config.bin %> <%= command.id %> my-api --output json',
];
AppStatus.args = {
    name: core_1.Args.string({
        description: 'Application name or slug',
        required: true,
    }),
};
AppStatus.flags = {
    cluster: core_1.Flags.string({
        char: 'c',
        description: 'Cluster name or ID (default: auto-detect when only one cluster exists)',
    }),
    output: core_1.Flags.string({
        char: 'o',
        description: 'Output format',
        options: ['table', 'json'],
        default: 'table',
    }),
};
exports.default = AppStatus;
