/*
 * Copyright 2024 KylinSoft Co., Ltd.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <https://www.gnu.org/licenses/>.
 */
#pragma once

#include <string>
#include <vector>

struct ImgBase64Result {
    std::string base64Result;
    std::string format;  // 图片format png、jpg、bmp
    int errorCode;       // 假设成功时 errorCode 为 -1
    std::string errorMessage;
};

template <size_t N>
std::string getFormatFromHeader(const unsigned char (&head)[N]) {
    // N 是编译期知道的数组长度，可用于边界检查
    const unsigned char *h = head;

    // 安全访问：先检查长度再访问
    if (N >= 3 && h[0] == 0xFF && h[1] == 0xD8 && h[2] == 0xFF) {
        return "jpg";
    }

    if (N >= 4 && h[0] == 0x89 && h[1] == 0x50 && h[2] == 0x4E && h[3] == 0x47) {
        return "png";
    }

    if (N >= 2 && h[0] == 'B' && h[1] == 'M') {
        return "bmp";
    }

    if (N >= 3 && h[0] == 'G' && h[1] == 'I' && h[2] == 'F') {
        return "gif";
    }

    // TIFF: 支持 "II*" 和 "MM\0*"
    if (N >= 4) {
        if ((h[0] == 'I' && h[1] == 'I' && h[2] == 0x2A) ||
            (h[0] == 'M' && h[1] == 'M' && h[2] == 0x00 && h[3] == 0x2A)) {
            return "tiff";
        }
    }
    // 本函数结果仅在图像生成阶段使用，编码器不支持的格式默认使用 JPG
    return "jpg";
}