/*
 * Copyright (c) 2025-2026 IB-Robot Group & openEuler Embedded SIG & openharmony-robot sig_RoboFrame.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#pragma once

#include <cctype>
#include <string>
#include <string_view>

namespace ibmw::common::util {

inline constexpr unsigned char MAX_DECIMAL_DIGIT = 9;
// Value of the hex digit 'A' / 'a'.
inline constexpr unsigned char HEX_LETTER_BASE_VALUE = 10;
inline constexpr int HEX_NIBBLE_BITS = 4;
// A percent escape is '%' followed by two hex digits.
inline constexpr size_t PERCENT_ESCAPE_HEX_DIGITS = 2;
inline constexpr size_t PERCENT_ESCAPE_LENGTH = 3;

inline unsigned char ToHex(unsigned char x, bool up)
{
    return x > MAX_DECIMAL_DIGIT ? x + (up ? 'A' : 'a') - HEX_LETTER_BASE_VALUE : (x + '0');
}

inline unsigned char FromHex(unsigned char x)
{
    if (x >= '0' && x <= '9') {
        return x - '0';
    }
    if (x >= 'A' && x <= 'F') {
        return x - 'A' + HEX_LETTER_BASE_VALUE;
    }
    if (x >= 'a' && x <= 'f') {
        return x - 'a' + HEX_LETTER_BASE_VALUE;
    }
    return 0;
}

inline bool IsHexDigit(unsigned char x)
{
    return (x >= '0' && x <= '9') || ((x | 0x20) >= 'a' && (x | 0x20) <= 'f');
}

// Decodes the "%XY" escape starting at str[i]; false if str[i + 1] and
// str[i + 2] are not two hex digits.
inline bool DecodePercentEscape(std::string_view str, size_t i, char& out)
{
    if (i + PERCENT_ESCAPE_HEX_DIGITS >= str.length()) {
        return false;
    }
    const auto high = static_cast<unsigned char>(str[i + 1]);
    const auto low = static_cast<unsigned char>(str[i + PERCENT_ESCAPE_HEX_DIGITS]);
    if (!IsHexDigit(high) || !IsHexDigit(low)) {
        return false;
    }
    out = static_cast<char>((FromHex(high) << HEX_NIBBLE_BITS) | FromHex(low));
    return true;
}

inline std::string UrlEncode(std::string_view str, bool up = true)
{
    std::string retStr;
    retStr.reserve(str.length() * PERCENT_ESCAPE_LENGTH);

    for (unsigned char c : str) {
        if (std::isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
            retStr += static_cast<char>(c);
        } else if (c == ' ') {
            retStr += '+';
        } else {
            retStr += '%';
            retStr += static_cast<char>(ToHex(c >> HEX_NIBBLE_BITS, up));
            retStr += static_cast<char>(ToHex(c & 0xF, up));
        }
    }
    return retStr;
}

inline std::string UrlDecode(std::string_view str)
{
    std::string retStr;
    retStr.reserve(str.length());

    size_t i = 0;
    while (i < str.length()) {
        if (str[i] == '+') {
            retStr += ' ';
        } else if (char decoded; str[i] == '%' && DecodePercentEscape(str, i, decoded)) {
            retStr += decoded;
            i += PERCENT_ESCAPE_HEX_DIGITS;
        } else {
            retStr += str[i];
        }
        ++i;
    }

    return retStr;
}

inline std::string HttpHeaderEncode(std::string_view str, bool up = true)
{
    std::string retStr;
    retStr.reserve(str.length() * PERCENT_ESCAPE_LENGTH);

    for (unsigned char c : str) {
        if (std::isalnum(c) || c == '-') {
            retStr += static_cast<char>(c);
        } else {
            retStr += '%';
            retStr += static_cast<char>(ToHex(c >> HEX_NIBBLE_BITS, up));
            retStr += static_cast<char>(ToHex(c & 0xF, up));
        }
    }
    return retStr;
}

inline std::string HttpHeaderDecode(std::string_view str)
{
    std::string retStr;
    retStr.reserve(str.length());

    size_t i = 0;
    while (i < str.length()) {
        if (char decoded; str[i] == '%' && DecodePercentEscape(str, i, decoded)) {
            retStr += decoded;
            i += PERCENT_ESCAPE_HEX_DIGITS;
        } else {
            retStr += str[i];
        }
        ++i;
    }
    return retStr;
}

} // namespace ibmw::common::util