"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");
const format_bytes_1 = require("../../lib/format-bytes");
class AppMetrics extends core_1.Command {
    async run() {
        const { args, flags } = await this.parse(AppMetrics);
        const spinner = (0, ora_1.default)(`Fetching metrics 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 res = await service.getMetrics(app.id);
            spinner.stop();
            if (flags.output === 'json') {
                console.log(JSON.stringify(res, null, 2));
                return;
            }
            const m = res.metrics;
            console.log(chalk_1.default.cyan(`\n  Metrics — ${res.app_name}`));
            console.log(chalk_1.default.dim(`  namespace=${res.namespace}  queried=${new Date(res.queried_at).toLocaleString()}\n`));
            console.log(chalk_1.default.bold('  CPU'));
            console.log(`    usage      ${this.fmtCores(m.cpu.usage_cores)}  /  req ${this.fmtCores(m.cpu.requests_cores)}  /  lim ${this.fmtCores(m.cpu.limits_cores)}`);
            console.log(`    utilization ${this.fmtPct(m.cpu.utilization_percent)}\n`);
            console.log(chalk_1.default.bold('  Memory'));
            console.log(`    usage      ${this.fmtBytes(m.memory.usage_bytes)}  /  req ${this.fmtBytes(m.memory.requests_bytes)}  /  lim ${this.fmtBytes(m.memory.limits_bytes)}`);
            console.log(`    utilization ${this.fmtPct(m.memory.utilization_percent)}\n`);
            console.log(chalk_1.default.bold('  Network'));
            console.log(`    rx         ${this.fmtRate(m.network.receive_bytes_rate)}`);
            console.log(`    tx         ${this.fmtRate(m.network.transmit_bytes_rate)}\n`);
            console.log(chalk_1.default.bold('  Replicas'));
            const s = m.status;
            console.log(`    desired=${s.replicas_desired ?? '-'}  ready=${s.replicas_ready ?? '-'}  unavailable=${s.replicas_unavailable ?? '-'}  up=${s.up ?? '-'}`);
            console.log(`    restarts   total=${s.restart_total ?? '-'}  rate(1h)=${s.restart_rate_1h ?? '-'}\n`);
            if (m.pods.length > 0) {
                console.log(chalk_1.default.bold('  Pods'));
                for (const p of m.pods) {
                    console.log(`    ${p.phase.padEnd(10)} ${p.count}`);
                }
                console.log('');
            }
        }
        catch (error) {
            spinner.fail('Failed to fetch metrics');
            console.log(chalk_1.default.red(`\n  Error: ${error.message}\n`));
            this.exit(1);
        }
    }
    fmtCores(v) {
        if (v === null || v === undefined)
            return chalk_1.default.dim('-');
        return `${v.toFixed(3)} cores`;
    }
    fmtBytes(v) {
        if (v === null || v === undefined)
            return chalk_1.default.dim('-');
        return (0, format_bytes_1.formatBytes)(v);
    }
    fmtRate(v) {
        if (v === null || v === undefined)
            return chalk_1.default.dim('-');
        return `${(0, format_bytes_1.formatBytes)(v)}/s`;
    }
    fmtPct(v) {
        if (v === null || v === undefined)
            return chalk_1.default.dim('-');
        return `${v.toFixed(1)}%`;
    }
}
AppMetrics.description = 'Show instant Prometheus metrics (CPU/mem/network/replicas) for an application';
AppMetrics.examples = [
    '<%= config.bin %> <%= command.id %> my-api',
    '<%= config.bin %> <%= command.id %> my-api --output json',
];
AppMetrics.args = {
    name: core_1.Args.string({
        description: 'Application name or slug',
        required: true,
    }),
};
AppMetrics.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 = AppMetrics;
