"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 AppList extends core_1.Command {
    async run() {
        const { flags } = await this.parse(AppList);
        const spinner = (0, ora_1.default)('Fetching applications...').start();
        try {
            const { id: clusterId } = await (0, resolve_cluster_1.resolveCluster)(flags.cluster);
            const service = await cli_app_service_1.CliAppService.create(clusterId);
            const apps = await service.listApps();
            spinner.stop();
            if (flags.output === 'json') {
                console.log(JSON.stringify(apps, null, 2));
                return;
            }
            if (apps.length === 0) {
                console.log(chalk_1.default.yellow('\n  No applications found in this cluster.\n'));
                return;
            }
            console.log(chalk_1.default.cyan('\n  Applications\n'));
            console.log(chalk_1.default.dim(`  ${'NAME'.padEnd(28)} ${'STATUS'.padEnd(14)} ${'REPLICAS'.padEnd(10)} ${'KIND'.padEnd(14)} ${'EXPOSURE'.padEnd(10)} LAST DEPLOY`));
            console.log(chalk_1.default.dim('  ' + '─'.repeat(90)));
            for (const app of apps) {
                const name = app.name.length > 26 ? app.name.slice(0, 25) + '…' : app.name;
                const kind = (app.kind || '').toLowerCase();
                const exposure = (app.exposure || '').toLowerCase();
                const replicas = String(app.replicas ?? '-');
                const lastDeploy = app.lastDeployedAt
                    ? new Date(app.lastDeployedAt).toLocaleString()
                    : chalk_1.default.dim('never');
                // Pad before coloring so escape codes don't break column widths
                const statusPadded = app.status.padEnd(14);
                const coloredStatus = this.colorStatus(statusPadded);
                console.log(`  ${name.padEnd(28)} ${coloredStatus} ${replicas.padEnd(10)} ${kind.padEnd(14)} ${exposure.padEnd(10)} ${lastDeploy}`);
            }
            console.log('');
            console.log(chalk_1.default.dim(`  ${apps.length} app${apps.length === 1 ? '' : 's'} total`));
            console.log('');
        }
        catch (error) {
            spinner.fail('Failed to fetch applications');
            console.log(chalk_1.default.red(`\n  Error: ${error.message}\n`));
            this.exit(1);
        }
    }
    colorStatus(status) {
        const s = status.trim().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);
    }
}
AppList.description = 'List all applications in the cluster';
AppList.examples = [
    '<%= config.bin %> <%= command.id %>',
    '<%= config.bin %> <%= command.id %> --output json',
];
AppList.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 = AppList;
