#include "image_processor_rga.h"

#if defined(ISF_ENABLE_RGA)

namespace inspire {

namespace nexus {

RgaImageProcessor::RgaImageProcessor() {
    // RGA 硬件要求 RGB888 stride 16 对齐
    aligned_width_ = 16;
}

RgaImageProcessor::~RgaImageProcessor() {}

int32_t RgaImageProcessor::GetAlignedWidth(int width) const {
    return aligned_width_;
}

void RgaImageProcessor::SetAlignedWidth(int width) {
    aligned_width_ = width;
}

int32_t RgaImageProcessor::Resize(const uint8_t* src_data, int src_width, int src_height, int channels, uint8_t** dst_data, int dst_width,
                                  int dst_height) {
    // RGA 硬件限制: 本机实测宽高须 >= kRgaMinDim (如活体输入 24x24 会失败),
    // 小尺寸回退到 CPU (InspireCV), 避免 RGA no core match / unsupported
    if (src_width < kRgaMinDim || src_height < kRgaMinDim || dst_width < kRgaMinDim || dst_height < kRgaMinDim) {
        inspirecv::Image src_img(src_width, src_height, channels, src_data, false);
        last_buffer_.image = src_img.Resize(dst_width, dst_height);
        *dst_data = last_buffer_.GetData();
        return 0;
    }
    // Calculate width aligned to 4 bytes
    int aligned_src_width = (src_width + aligned_width_ - 1) & ~(aligned_width_ - 1);  // Round up to nearest multiple of aligned_width_
    int aligned_dst_width = (dst_width + aligned_width_ - 1) & ~(aligned_width_ - 1);
    // std::cout << "aligned_src_width: " << aligned_src_width << ", aligned_dst_width: " << aligned_dst_width << std::endl;

    // 1. Get or create source buffer with aligned width
    BufferKey src_key{aligned_src_width, src_height, channels};
    auto& src_buffer = GetOrCreateBuffer(src_key);

    // 2. Get or create destination buffer with aligned width
    BufferKey dst_key{aligned_dst_width, dst_height, channels};
    auto& dst_buffer = GetOrCreateBuffer(dst_key, false);

    // 3. Copy source data to RGA buffer, handle padding row by row
    for (int y = 0; y < src_height; y++) {
        memcpy(static_cast<uint8_t*>(src_buffer.virtual_addr) + y * aligned_src_width * channels, src_data + y * src_width * channels,
               src_width * channels);
        // Padding area remains zero
    }

    dma_sync_cpu_to_device(src_buffer.dma_fd);
    dma_sync_cpu_to_device(dst_buffer.dma_fd);

    // 4. Execute RGA resize
    int ret = imcheck(src_buffer.buffer, dst_buffer.buffer, {}, {});
    if (IM_STATUS_NOERROR != ret) {
        INSPIRECV_LOG(ERROR) << "RGA parameter check failed: " << imStrError((IM_STATUS)ret);
        return -1;
    }

    ret = imresize(src_buffer.buffer, dst_buffer.buffer);

    if (ret != IM_STATUS_SUCCESS) {
        INSPIRECV_LOG(ERROR) << "RGA resize failed: " << imStrError((IM_STATUS)ret);
        return -1;
    }

    // 5. Return pointer to destination buffer
    *dst_data = static_cast<uint8_t*>(dst_buffer.virtual_addr);

    return 0;
}

int32_t RgaImageProcessor::MarkDone() {
    // Sync all buffers
    for (const auto& pair : buffer_cache_) {
        dma_sync_device_to_cpu(pair.second.dma_fd);
    }

    // // Print current cache status for debugging
    // INSPIRECV_LOG(INFO) << "MarkDone: Current cache status:";
    // INSPIRECV_LOG(INFO) << "Cache size: " << buffer_cache_.size();
    // for (const auto& pair : buffer_cache_) {
    //     INSPIRECV_LOG(INFO) << "Buffer: " << pair.second.width << "x" << pair.second.height << " dma_fd=" << pair.second.dma_fd;
    // }
    return 0;
}

int32_t RgaImageProcessor::SwapColor(const uint8_t* src_data, int src_width, int src_height, int channels, uint8_t** dst_data) {
    // RGA 硬件限制: 小尺寸回退 CPU
    if (src_width < kRgaMinDim || src_height < kRgaMinDim) {
        inspirecv::Image src_img(src_width, src_height, channels, src_data, false);
        last_buffer_.image = src_img.SwapRB();
        *dst_data = last_buffer_.GetData();
        return 0;
    }
    // Calculate width aligned to 4 bytes
    int aligned_src_width = (src_width + aligned_width_ - 1) & ~(aligned_width_ - 1);  // Round up to nearest multiple of aligned_width_
    // 1. Get or create source buffer
    BufferKey src_key{aligned_src_width, src_height, channels};
    auto& src_buffer = GetOrCreateBuffer(src_key);

    // 2. Get or create destination buffer
    BufferKey dst_key{aligned_src_width, src_height, channels};
    auto& dst_buffer = GetOrCreateBuffer(dst_key, false);

    // 3. Copy source data to RGA buffer, handle padding row by row
    for (int y = 0; y < src_height; y++) {
        memcpy(static_cast<uint8_t*>(src_buffer.virtual_addr) + y * aligned_src_width * channels, src_data + y * src_width * channels,
               src_width * channels);
        // Padding area remains zero
    }

    dma_sync_cpu_to_device(src_buffer.dma_fd);
    dma_sync_cpu_to_device(dst_buffer.dma_fd);

    // 3. Execute RGA swap color
    int ret = imcheck(src_buffer.buffer, dst_buffer.buffer, {}, {});
    if (IM_STATUS_NOERROR != ret) {
        INSPIRECV_LOG(ERROR) << "RGA parameter check failed: " << imStrError((IM_STATUS)ret);
        return -1;
    }

    // 4. Execute RGA swap color
    ret = imcvtcolor(src_buffer.buffer, dst_buffer.buffer, RK_FORMAT_RGB_888, RK_FORMAT_BGR_888);
    if (ret != IM_STATUS_SUCCESS) {
        INSPIRECV_LOG(ERROR) << "RGA color conversion failed: " << imStrError((IM_STATUS)ret);
        return -1;
    }

    dma_sync_device_to_cpu(dst_buffer.dma_fd);

    // 5. Return pointer to destination buffer
    *dst_data = static_cast<uint8_t*>(dst_buffer.virtual_addr);

    return 0;
}

int32_t RgaImageProcessor::Padding(const uint8_t* src_data, int src_width, int src_height, int channels, int top, int bottom, int left, int right,
                                   uint8_t** dst_data, int& dst_width, int& dst_height) {
    // Calculate final dimensions
    dst_width = src_width + left + right;
    dst_height = src_height + top + bottom;

    // RGA 硬件限制: 小尺寸回退 CPU
    if (src_width < kRgaMinDim || src_height < kRgaMinDim || dst_width < kRgaMinDim || dst_height < kRgaMinDim) {
        inspirecv::Image src_img(src_width, src_height, channels, src_data, false);
        last_buffer_.image = src_img.Pad(top, bottom, left, right, inspirecv::Color::Black);
        *dst_data = last_buffer_.GetData();
        return 0;
    }

    // Calculate width aligned to 4 bytes
    int aligned_src_width = (src_width + aligned_width_ - 1) & ~(aligned_width_ - 1);  // Round up to nearest multiple of aligned_width_
    int aligned_dst_width = (dst_width + aligned_width_ - 1) & ~(aligned_width_ - 1);  // Round up to nearest multiple of aligned_width_

    // 1. Get or create source buffer with aligned width
    BufferKey src_key{aligned_src_width, src_height, channels};
    auto& src_buffer = GetOrCreateBuffer(src_key, true);

    // 2. Create destination buffer with padded dimensions
    BufferKey dst_key{aligned_dst_width, dst_height, channels};
    auto& dst_buffer = GetOrCreateBuffer(dst_key, false);

    // 3. Copy source data to RGA buffer
    for (int y = 0; y < src_height; y++) {
        memcpy(static_cast<uint8_t*>(src_buffer.virtual_addr) + y * aligned_src_width * channels, src_data + y * src_width * channels,
               src_width * channels);
    }

    dma_sync_cpu_to_device(src_buffer.dma_fd);
    dma_sync_cpu_to_device(dst_buffer.dma_fd);

    // 4. Execute padding operation
    // Set source and destination regions
    im_rect src_rect = {0, 0, src_width, src_height};
    im_rect dst_rect = {left, top, src_width, src_height};  // Specify padding position

    int ret = imcheck(src_buffer.buffer, dst_buffer.buffer, src_rect, dst_rect);
    if (IM_STATUS_NOERROR != ret) {
        INSPIRECV_LOG(ERROR) << "RGA parameter check failed: " << imStrError((IM_STATUS)ret);
        return -1;
    }

    // 5. 用 CPU 填充黑色 — 本机 librga 2.1.0 的 imfill 与内核 RGA 驱动不兼容
    //    (dmesg: failed to map buffer), imresize/improcess 正常;
    //    dma-buf 已 mmap(virtual_addr), memset 后重新刷 cache 给设备
    memset(dst_buffer.virtual_addr, 0x00, (size_t)aligned_dst_width * dst_height * channels);
    dma_sync_cpu_to_device(dst_buffer.dma_fd);

    // 6. Copy source image to specified position in destination
    ret = improcess(src_buffer.buffer, dst_buffer.buffer, {}, src_rect, dst_rect, {}, IM_SYNC);
    if (ret != IM_STATUS_SUCCESS) {
        INSPIRECV_LOG(ERROR) << "RGA copy failed: " << imStrError((IM_STATUS)ret);
        return -1;
    }

    dma_sync_device_to_cpu(dst_buffer.dma_fd);

    *dst_data = static_cast<uint8_t*>(dst_buffer.virtual_addr);
    return 0;
}

int32_t RgaImageProcessor::ResizeAndPadding(const uint8_t* src_data, int src_width, int src_height, int channels, int dst_width, int dst_height,
                                            uint8_t** dst_data, float& scale) {
    // RGA 硬件限制: 小尺寸回退 CPU
    if (src_width < kRgaMinDim || src_height < kRgaMinDim || dst_width < kRgaMinDim || dst_height < kRgaMinDim) {
        inspirecv::Image src_img(src_width, src_height, channels, src_data, false);
        scale = std::min(static_cast<float>(dst_width) / src_width, static_cast<float>(dst_height) / src_height);
        int resized_w = static_cast<int>(src_width * scale);
        int resized_h = static_cast<int>(src_height * scale);
        int wpad = dst_width - resized_w;
        int hpad = dst_height - resized_h;
        inspirecv::Image resized_img = src_img.Resize(resized_w, resized_h);
        last_buffer_.image = resized_img.Pad(0, hpad, 0, wpad, inspirecv::Color::Black);
        *dst_data = last_buffer_.GetData();
        return 0;
    }
    // Ensure target dimensions are multiples of 4
    int aligned_dst_width = (dst_width + aligned_width_ - 1) & ~(aligned_width_ - 1);  // Round up to nearest multiple of aligned_width_
    int aligned_dst_height = (dst_height + aligned_width_ - 1) & ~(aligned_width_ - 1);  // Round up to nearest multiple of aligned_width_

    // Calculate scale (take minimum to fit target box)
    scale = std::min(static_cast<float>(aligned_dst_width) / src_width, static_cast<float>(aligned_dst_height) / src_height);

    // Calculate scaled dimensions
    int resized_w = static_cast<int>(src_width * scale);
    int resized_h = static_cast<int>(src_height * scale);

    // Ensure scaled dimensions are multiples of 4
    resized_w = (resized_w + aligned_width_ - 1) & ~(aligned_width_ - 1);  // Round up to nearest multiple of aligned_width_
    resized_h = (resized_h + aligned_width_ - 1) & ~(aligned_width_ - 1);  // Round up to nearest multiple of aligned_width_

    int aligned_src_width = (src_width + aligned_width_ - 1) & ~(aligned_width_ - 1);  // Round up to nearest multiple of aligned_width_

    // 1. Get source buffer
    BufferKey src_key{aligned_src_width, src_height, channels};
    auto& src_buffer = GetOrCreateBuffer(src_key);

    // 2. Get destination buffer
    BufferKey dst_key{aligned_dst_width, aligned_dst_height, channels};
    auto& dst_buffer = GetOrCreateBuffer(dst_key, false);

    // 3. Copy source data to RGA buffer
    for (int y = 0; y < src_height; y++) {
        memcpy(static_cast<uint8_t*>(src_buffer.virtual_addr) + y * aligned_src_width * channels, src_data + y * src_width * channels,
               src_width * channels);
    }

    dma_sync_cpu_to_device(src_buffer.dma_fd);
    dma_sync_cpu_to_device(dst_buffer.dma_fd);

    // 4. Set source and destination regions
    im_rect src_rect = {0, 0, src_width, src_height};
    im_rect dst_rect = {0, 0, resized_w, resized_h};  // Image placed in top-left corner

    int ret = imcheck(src_buffer.buffer, dst_buffer.buffer, src_rect, dst_rect);
    if (IM_STATUS_NOERROR != ret) {
        INSPIRECV_LOG(ERROR) << "RGA parameter check failed: " << imStrError((IM_STATUS)ret);
        return -1;
    }

    // 5. 用 CPU 填充黑色 — 本机 librga 2.1.0 的 imfill 与内核 RGA 驱动不兼容
    //    (dmesg: failed to map buffer), imresize/improcess 正常;
    //    dma-buf 已 mmap(virtual_addr), memset 后重新刷 cache 给设备
    memset(dst_buffer.virtual_addr, 0x00, (size_t)aligned_dst_width * aligned_dst_height * channels);
    dma_sync_cpu_to_device(dst_buffer.dma_fd);

    // 6. Execute resize operation, image will be placed in top-left corner
    ret = improcess(src_buffer.buffer, dst_buffer.buffer, {}, src_rect, dst_rect, {}, IM_SYNC);
    if (ret != IM_STATUS_SUCCESS) {
        INSPIRECV_LOG(ERROR) << "RGA resize failed: " << imStrError((IM_STATUS)ret);
        return -1;
    }

    dma_sync_device_to_cpu(dst_buffer.dma_fd);

    // 7. Return processed data
    *dst_data = static_cast<uint8_t*>(dst_buffer.virtual_addr);
    return 0;
}

}  // namespace nexus

}  // namespace inspire

#endif  // ISF_ENABLE_RGA