"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 AppLogs extends core_1.Command {
    async run() {
        const { args, flags } = await this.parse(AppLogs);
        const spinner = (0, ora_1.default)(`Fetching logs 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 result = await service.getLogs({
                app: app.slug || app.name,
                namespace: flags.namespace,
                level: flags.level,
                tail: flags.tail,
                search: flags.search,
            });
            spinner.stop();
            if (flags.output === 'json') {
                console.log(JSON.stringify(result, null, 2));
                return;
            }
            if (result.logs.length === 0) {
                const levelHint = flags.level ? ` at level "${flags.level}"` : '';
                console.log(chalk_1.default.yellow(`\n  No logs found for "${args.name}"${levelHint}.\n`));
                return;
            }
            const header = flags.level
                ? chalk_1.default.cyan(`\n  Logs for ${args.name} (level: ${flags.level}) — ${result.count} lines\n`)
                : chalk_1.default.cyan(`\n  Logs for ${args.name} — ${result.count} lines\n`);
            console.log(header);
            for (const entry of result.logs) {
                const time = chalk_1.default.dim(new Date(entry.timestamp)
                    .toISOString()
                    .replace('T', ' ')
                    .slice(0, 23));
                const level = this.colorLevel(entry.level);
                const pod = entry.pod
                    ? chalk_1.default.dim(`[${entry.pod.split('-').slice(-2).join('-')}]`)
                    : '';
                console.log(`  ${time} ${level} ${pod} ${entry.message}`);
            }
            console.log('');
            console.log(chalk_1.default.dim(`  Queried at: ${result.queried_at}`));
            console.log('');
        }
        catch (error) {
            spinner.fail('Failed to fetch logs');
            console.log(chalk_1.default.red(`\n  Error: ${error.message}\n`));
            this.exit(1);
        }
    }
    colorLevel(level) {
        if (!level)
            return '     ';
        const padded = level.toUpperCase().padEnd(5);
        switch (level.toLowerCase()) {
            case 'error':
                return chalk_1.default.red(padded);
            case 'warn':
                return chalk_1.default.yellow(padded);
            case 'info':
                return chalk_1.default.blue(padded);
            case 'debug':
                return chalk_1.default.dim(padded);
            default:
                return chalk_1.default.white(padded);
        }
    }
}
AppLogs.description = 'Fetch logs for an application';
AppLogs.examples = [
    '<%= config.bin %> <%= command.id %> my-api',
    '<%= config.bin %> <%= command.id %> my-api --level error',
    '<%= config.bin %> <%= command.id %> my-api --tail 500',
    '<%= config.bin %> <%= command.id %> my-api --search "connection refused"',
];
AppLogs.args = {
    name: core_1.Args.string({
        description: 'Application name or slug',
        required: true,
    }),
};
AppLogs.flags = {
    cluster: core_1.Flags.string({
        char: 'c',
        description: 'Cluster name or ID (default: auto-detect when only one cluster exists)',
    }),
    level: core_1.Flags.string({
        char: 'l',
        description: 'Filter by log level',
        options: ['error', 'warn', 'info', 'debug'],
    }),
    tail: core_1.Flags.integer({
        char: 'n',
        description: 'Number of lines to return',
        default: 100,
    }),
    search: core_1.Flags.string({
        char: 's',
        description: 'Full-text search query',
    }),
    namespace: core_1.Flags.string({
        description: 'Kubernetes namespace (optional, auto-detected from app)',
    }),
    output: core_1.Flags.string({
        char: 'o',
        description: 'Output format',
        options: ['text', 'json'],
        default: 'text',
    }),
};
exports.default = AppLogs;
