"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.ErrorHandler = exports.CLIError = exports.ErrorCode = void 0;
const logger_1 = require("./logger");
const colors_1 = require("./colors");
const clack = __importStar(require("@clack/prompts"));
const config_service_1 = require("../services/config/config.service");
const fs_1 = require("fs");
const Sentry = __importStar(require("@sentry/node"));
const delay_1 = require("./delay");
var ErrorCode;
(function (ErrorCode) {
    ErrorCode[ErrorCode["GENERAL"] = 1] = "GENERAL";
    ErrorCode[ErrorCode["INVALID_CONFIG"] = 2] = "INVALID_CONFIG";
    ErrorCode[ErrorCode["NETWORK_ERROR"] = 3] = "NETWORK_ERROR";
    ErrorCode[ErrorCode["FILE_SYSTEM_ERROR"] = 4] = "FILE_SYSTEM_ERROR";
    ErrorCode[ErrorCode["COMPONENT_ERROR"] = 5] = "COMPONENT_ERROR";
    ErrorCode[ErrorCode["VALIDATION_ERROR"] = 6] = "VALIDATION_ERROR";
    ErrorCode[ErrorCode["PERMISSION_ERROR"] = 7] = "PERMISSION_ERROR";
    ErrorCode[ErrorCode["NOT_FOUND"] = 8] = "NOT_FOUND";
    ErrorCode[ErrorCode["BUILD_ERROR"] = 9] = "BUILD_ERROR";
})(ErrorCode || (exports.ErrorCode = ErrorCode = {}));
class CLIError extends Error {
    code;
    cause;
    suggestions;
    showLogPath;
    constructor(message, options = {}) {
        super(message);
        this.name = 'CLIError';
        this.code = options.code ?? ErrorCode.GENERAL;
        this.cause = options.cause;
        this.suggestions = options.suggestions ?? [];
        this.showLogPath = options.showLogPath ?? true;
    }
}
exports.CLIError = CLIError;
class ErrorHandler {
    static logger = logger_1.Logger.getInstance("error.handler");
    static async handle(error) {
        this.logger.error((0, colors_1.red)('✖'), (0, colors_1.bold)('Error:'), error);
        if (error.cause) {
            this.logger.error('Caused by:', error.cause);
        }
        const exitCode = error instanceof CLIError ? error.code : ErrorCode.GENERAL;
        if (error instanceof CLIError) { // Show suggestions if available
            if (error.suggestions.length > 0) {
                clack.note(error.suggestions.map(suggestion => (0, colors_1.yellow)(`  • ${suggestion}`)).join('\n'), "Suggestions:");
            }
            // Show log path for troubleshooting
            if (error.showLogPath) {
                this.logger.error((0, colors_1.gray)('For detailed logs, check:'));
                this.logger.error((0, colors_1.gray)('  ' + this.logger.getLogPath()));
            }
        }
        else {
            // Generic error handling
            this.logger.error((0, colors_1.gray)('For detailed logs, check:'));
            this.logger.error((0, colors_1.gray)('  ' + this.logger.getLogPath()));
        }
        // Ensure all logs are flushed before exit
        this.logger.flush();
        // Give a small delay to ensure flush completes, then exit
        await (0, delay_1.delay)(100);
        if (config_service_1.ConfigManager.config.sentry) {
            this.sendToSentry(error);
            // Wait a bit to ensure Sentry sends the error before exiting
            await (0, delay_1.delay)(100);
        }
        process.exit(exitCode);
    }
    static wrap(fn) {
        return fn().catch(error => {
            this.handle(error);
        });
    }
    static sendToSentry(error) {
        try {
            Sentry.withScope((scope) => {
                // Set error context
                scope.setTag('errorCode', error instanceof CLIError ? error.code : 'GENERAL');
                scope.setLevel('error');
                // Add log file as attachment
                try {
                    const logContent = (0, fs_1.readFileSync)(this.logger.getLogPath(), 'utf8');
                    scope.addAttachment({
                        filename: 'cli.log',
                        data: logContent,
                        contentType: 'text/plain'
                    });
                }
                catch (logError) {
                    console.error('Failed to attach log file to Sentry:', logError);
                }
                // Add CLI-specific context
                scope.setContext('cli', {
                    version: require('../../package.json').version,
                    command: process.argv.slice(2).join(' '),
                    platform: process.platform,
                    nodeVersion: process.version
                });
                // Capture the error
                Sentry.captureException(error);
            });
        }
        catch (sentryError) {
            console.error('Failed to send error to Sentry:', sentryError);
        }
    }
}
exports.ErrorHandler = ErrorHandler;
//# sourceMappingURL=error.handler.js.map