"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 AppCrashes extends core_1.Command {
    async run() {
        const { args, flags } = await this.parse(AppCrashes);
        const spinner = (0, ora_1.default)(`Fetching crash reports 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 diagnoses = await service.getCrashes(app.id);
            spinner.stop();
            if (flags.output === 'json') {
                console.log(JSON.stringify(diagnoses, null, 2));
                return;
            }
            const open = diagnoses.filter((d) => !d.resolvedAt);
            const resolved = diagnoses.filter((d) => d.resolvedAt);
            if (diagnoses.length === 0) {
                console.log(chalk_1.default.green(`\n  No crash reports for "${args.name}".\n`));
                return;
            }
            console.log(chalk_1.default.cyan(`\n  Crash Reports — ${args.name}\n`));
            if (open.length > 0) {
                console.log(chalk_1.default.bold('  Active\n'));
                for (const d of open)
                    this.printActiveDiagnosis(d);
            }
            if (resolved.length > 0) {
                console.log(chalk_1.default.dim(`  ${resolved.length} resolved crash(es) not shown.`));
                console.log('');
            }
            console.log(chalk_1.default.dim(`  ${open.length} active, ${resolved.length} resolved — total ${diagnoses.length}`));
            console.log('');
        }
        catch (error) {
            spinner.fail('Failed to fetch crash reports');
            console.log(chalk_1.default.red(`\n  Error: ${error.message}\n`));
            this.exit(1);
        }
    }
    printActiveDiagnosis(d) {
        const icon = d.severity === 'critical' ? chalk_1.default.red('✖') : chalk_1.default.yellow('⚠');
        console.log(`  ${icon} ${chalk_1.default.bold(d.title)}`);
        console.log(`    ${chalk_1.default.dim('category:')}  ${d.category}`);
        console.log(`    ${chalk_1.default.dim('pod:')}       ${d.podName}`);
        console.log(`    ${chalk_1.default.dim('severity:')}  ${this.colorSeverity(d.severity)}`);
        console.log(`    ${chalk_1.default.dim('detected:')}  ${new Date(d.createdAt).toLocaleString()}`);
        if (d.explanation) {
            console.log(`    ${chalk_1.default.dim('reason:')}    ${d.explanation}`);
        }
        if (d.suggestedAction?.summary) {
            console.log(`    ${chalk_1.default.dim('action:')}    ${d.suggestedAction.summary}`);
        }
        console.log('');
    }
    colorSeverity(severity) {
        switch (severity) {
            case 'critical':
                return chalk_1.default.red(severity);
            case 'warning':
                return chalk_1.default.yellow(severity);
            default:
                return chalk_1.default.dim(severity);
        }
    }
}
AppCrashes.description = 'Show recent crash diagnoses for an application';
AppCrashes.examples = [
    '<%= config.bin %> <%= command.id %> my-api',
    '<%= config.bin %> <%= command.id %> my-api --output json',
];
AppCrashes.args = {
    name: core_1.Args.string({
        description: 'Application name or slug',
        required: true,
    }),
};
AppCrashes.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 = AppCrashes;
