#ifndef RTX_BASE_EXCEPTION_H
#define RTX_BASE_EXCEPTION_H

#include <exception>
#include <string>
#include <sstream>
#include "ErrorCode.h"

namespace rtx
{
    namespace exception
    {
        class BaseException : public std::exception
        {
        public:
            BaseException(ErrorCode code,
                          const std::string &message,
                          const char *file,
                          int line,
                          const char *function)
                : code_(code),
                  message_(message),
                  file_(file),
                  line_(line),
                  function_(function)
            {
                buildWhatString();
            }

            ErrorCode code() const noexcept { return code_; }
            const char *file() const noexcept { return file_; }
            int line() const noexcept { return line_; }
            const char *function() const noexcept { return function_; }
            const char *what() const noexcept override { return what_.c_str(); }

        protected:
            virtual void buildWhatString()
            {
                std::ostringstream oss;
                oss << "[EXCEPTION][" << static_cast<int>(code_) << "]\n"
                    << "Location: " << file_ << ":" << line_
                    << " in " << function_ << "\n"
                    << "Message: " << message_;
                what_ = oss.str();
            }

            static const char *codeToString(ErrorCode code)
            {
                switch (code)
                {
                case ErrorCode::INVALID_ARGUMENT:
                    return "INVALID_ARGUMENT";
                case ErrorCode::CONFIG_FILE_NOT_FOUND:
                    return "CONFIG_FILE_NOT_FOUND";
                case ErrorCode::SERIALIZE_INVALID_ENUM_VALUE:
                    return "SERIALIZE_INVALID_ENUM_VALUE";
                default:
                    return "UNKNOWN";
                }
            }

        private:
            ErrorCode code_;
            std::string message_;
            const char *file_;
            int line_;
            const char *function_;
            std::string what_;
        
        };
    }
}

// 基础异常宏
#define THROW_EXCEPTION(code, msg) \
    throw rtx::exception::BaseException(code, msg, __FILE__, __LINE__, __func__)

// 参数检查宏（自动填充错误信息）
#define CHECK_ARGUMENT(condition) \
    if (!(condition)) { \
        THROW_EXCEPTION(rtx::exception::ErrorCode::INVALID_ARGUMENT, \
                       "Argument check failed: " #condition); \
    }

#endif