#pragma once

#include <extra2d/graphics/resources/framebuffer.h>
#include <glad/glad.h>
#include <array>
#include <cstdint>

namespace extra2d {

// ============================================================================
// OpenGL 帧缓冲实现
// ============================================================================
class GLFramebuffer : public Framebuffer {
public:
    // 最大颜色附件数
    static constexpr int MAX_COLOR_ATTACHMENTS = 8;

    /**
     * @brief 构造函数
     */
    GLFramebuffer();

    /**
     * @brief 析构函数
     */
    ~GLFramebuffer() override;

    /**
     * @brief 初始化帧缓冲
     * @param desc 帧缓冲描述
     * @return 成功返回 true
     */
    bool init(const FramebufferDesc& desc);

    /**
     * @brief 关闭帧缓冲，释放资源
     */
    void shutdown();

    // Framebuffer 接口实现
    void bind() override;
    void unbind() override;
    void attachColorTexture(Ptr<Texture> texture, int attachment = 0) override;
    void attachDepthTexture(Ptr<Texture> texture) override;
    void attachDepthStencilTexture(Ptr<Texture> texture) override;
    bool isComplete() override;
    Ptr<Texture> getColorTexture(int attachment = 0) const override;
    Ptr<Texture> getDepthTexture() const override;
    int getWidth() const override { return width_; }
    int getHeight() const override { return height_; }
    Size getSize() const override { return Size(static_cast<float>(width_), static_cast<float>(height_)); }
    bool isValid() const override { return fboID_ != 0; }
    uintptr_t getNativeHandle() const override { return static_cast<uintptr_t>(fboID_); }
    void clear(const Color& color, bool clearColor = true, 
               bool clearDepth = true, bool clearStencil = false) override;
    void setViewport(int x, int y, int width, int height) override;
    bool readPixels(int x, int y, int width, int height, 
                    std::vector<uint8_t>& outData) override;

    /**
     * @brief 获取 OpenGL FBO ID
     * @return FBO ID
     */
    GLuint getFboID() const { return fboID_; }

    /**
     * @brief 创建带内置纹理的帧缓冲（便捷方法）
     * @param width 宽度
     * @param height 高度
     * @param colorFormat 颜色格式
     * @param depthFormat 深度格式（可选）
     * @return 成功返回 true
     */
    bool createWithTextures(int width, int height, 
                            PixelFormat colorFormat = PixelFormat::RGBA8,
                            PixelFormat depthFormat = PixelFormat::Depth24);

private:
    GLuint fboID_ = 0;
    int width_ = 0;
    int height_ = 0;
    int numColorAttachments_ = 1;
    bool hasDepth_ = false;
    bool hasStencil_ = false;

    // 附件纹理
    std::array<Ptr<Texture>, MAX_COLOR_ATTACHMENTS> colorTextures_;
    Ptr<Texture> depthTexture_;
    Ptr<Texture> depthStencilTexture_;

    // 是否为内置纹理（需要自动清理）
    bool hasInternalTextures_ = false;

    /**
     * @brief 检查并更新完整状态
     */
    bool checkStatus();

    /**
     * @brief 获取 OpenGL 附件枚举
     */
    static GLenum getColorAttachment(int index);
};

} // namespace extra2d
