"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 nest_app_1 = require("../../lib/nest-app");
const cli_logger_service_1 = require("../../services/cli-logger.service");
const cli_operation_repository_1 = require("../../lib/repositories/cli-operation.repository");
const context_banner_1 = require("../../lib/context-banner");
class EnvLogs extends core_1.Command {
    async run() {
        try {
            const { flags } = await this.parse(EnvLogs);
            (0, context_banner_1.printContextBanner)();
            const app = await (0, nest_app_1.getNestApp)();
            const loggerService = app.get(cli_logger_service_1.CliLoggerService);
            const operationRepo = app.get(cli_operation_repository_1.CliOperationRepository);
            // List all operations
            if (flags.list) {
                const operations = await operationRepo.find({
                    order: { createdAt: 'DESC' },
                });
                if (operations.length === 0) {
                    console.log(chalk_1.default.yellow('\nNo operations found.\n'));
                    return;
                }
                console.log(chalk_1.default.cyan('\n📜 Operations:\n'));
                for (const op of operations) {
                    const statusColor = this.getStatusColor(op.status);
                    const hasLogs = loggerService.hasLog(op.id);
                    const logsIndicator = hasLogs ? chalk_1.default.green('✓') : chalk_1.default.dim('-');
                    console.log(`   ${logsIndicator} ${chalk_1.default.bold(op.id)}`);
                    console.log(`      Type: ${op.operationType}`);
                    console.log(`      Status: ${statusColor(op.status)}`);
                    console.log(`      Created: ${op.createdAt.toLocaleString()}`);
                    if (hasLogs) {
                        const logsCmd = chalk_1.default.cyan(`flui env logs --operation ${op.id}`);
                        console.log(`      View logs: ${logsCmd}`);
                    }
                    console.log('');
                }
                return;
            }
            // Determine which operation to show logs for
            let operationId = flags.operation;
            if (!operationId) {
                // Find most recent operation
                const operations = await operationRepo.find({
                    order: { createdAt: 'DESC' },
                });
                if (operations.length === 0) {
                    console.log(chalk_1.default.yellow('\nNo operations found.\n'));
                    console.log(chalk_1.default.dim('Create a cluster first:'));
                    console.log(`   ${chalk_1.default.cyan('flui env create')}\n`);
                    return;
                }
                operationId = operations[0].id;
                console.log(chalk_1.default.dim(`\nShowing logs for most recent operation: ${operationId}\n`));
            }
            // Check if logs exist
            if (!loggerService.hasLog(operationId)) {
                console.log(chalk_1.default.yellow(`\nNo logs found for operation: ${operationId}\n`));
                console.log(chalk_1.default.dim('Available operations with logs:'));
                const logsIds = loggerService.listLogs();
                if (logsIds.length > 0) {
                    logsIds.forEach((id) => {
                        console.log(`   - ${id}`);
                    });
                }
                else {
                    console.log(`   ${chalk_1.default.dim('(none)')}`);
                }
                console.log('');
                return;
            }
            // Display logs
            const logs = loggerService.tailLog(operationId, flags.tail);
            console.log(chalk_1.default.cyan(`\n📋 Operation Logs: ${operationId}\n`));
            console.log(chalk_1.default.dim('─'.repeat(80)));
            console.log(logs);
            console.log(chalk_1.default.dim('─'.repeat(80)));
            console.log('');
            // Show real-time monitoring hint
            if (flags.tail < 1000) {
                console.log(chalk_1.default.dim('💡 Tip: Use --tail 1000 to see more lines\n'));
            }
        }
        catch (error) {
            console.log(chalk_1.default.red('\n❌ Error:\n'));
            if (error instanceof Error) {
                console.log(`   ${error.message}\n`);
            }
            else {
                console.log(`   ${String(error)}\n`);
            }
            this.exit(1);
        }
        finally {
            await (0, nest_app_1.closeNestApp)();
        }
    }
    getStatusColor(status) {
        const colors = {
            PENDING: chalk_1.default.yellow,
            IN_PROGRESS: chalk_1.default.blue,
            COMPLETED: chalk_1.default.green,
            FAILED: chalk_1.default.red,
        };
        return colors[status] || chalk_1.default.white;
    }
}
EnvLogs.description = 'View operation logs in real-time or retrospectively';
EnvLogs.examples = [
    '<%= config.bin %> <%= command.id %>',
    '<%= config.bin %> <%= command.id %> --tail 50',
    '<%= config.bin %> <%= command.id %> --operation op_123',
];
EnvLogs.flags = {
    tail: core_1.Flags.integer({
        char: 't',
        description: 'Number of lines to show from the end',
        default: 100,
    }),
    operation: core_1.Flags.string({
        char: 'o',
        description: 'Specific operation ID to view logs for',
    }),
    list: core_1.Flags.boolean({
        char: 'l',
        description: 'List all operations with logs',
        default: false,
    }),
};
exports.default = EnvLogs;
