/*
 * 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 <algorithm>
#include <charconv>
#include <cstdint>
#include <cstring>
#include <iomanip>
#include <map>
#include <regex>
#include <set>
#include <sstream>
#include <string>
#include <vector>

namespace ibmw::common::util {

/**
 * @brief trim string
 */
inline std::string& Trim(std::string& s)
{
    if (s.empty()) {
        return s;
    }
    s.erase(s.find_last_not_of(' ') + 1);
    s.erase(0, s.find_first_not_of(' '));
    return s;
}

inline std::string_view& Trim(std::string_view& s)
{
    if (s.empty()) {
        return s;
    }
    auto p = s.find_last_not_of(' ');
    s = s.substr(0, (p != std::string_view::npos) ? (p + 1) : 0);
    p = s.find_first_not_of(' ');
    s = s.substr((p != std::string_view::npos) ? p : s.size());
    return s;
}

/**
 * @brief split string to vector
 */
template <class StringType = std::string_view>
    requires(std::is_same_v<StringType, std::string_view> || std::is_same_v<StringType, std::string>)
inline std::vector<StringType> SplitToVec(std::string_view source, std::string_view sep, bool trim = true,
                                          bool clear = true)
{
    std::vector<StringType> result;
    if (source.empty() || sep.empty()) {
        return result;
    }

    size_t posEnd = 0;
    size_t posStart = 0;
    do {
        posEnd = source.find(sep, posStart);
        if (posEnd == std::string_view::npos) {
            posEnd = source.length();
        }

        auto subStr = source.substr(posStart, posEnd - posStart);

        if (trim) {
            Trim(subStr);
        }

        if (!(clear && subStr.empty())) {
            result.emplace_back(subStr);
        }

        posStart = posEnd + sep.size();
    } while (posEnd < source.length());

    return result;
}

/**
 * @brief splicing vector to string
 */
template <class StringType = std::string_view>
    requires(std::is_same_v<StringType, std::string_view> || std::is_same_v<StringType, std::string>)
inline std::string JoinVec(const std::vector<StringType>& vec, std::string_view sep)
{
    std::string result;
    for (auto itr = vec.begin(); itr != vec.end(); ++itr) {
        if (itr != vec.begin()) {
            result += sep;
        }
        result += *itr;
    }
    return result;
}

/**
 * @brief splits the string to set, automatically deduplicates
 */
template <class StringType = std::string_view>
    requires(std::is_same_v<StringType, std::string_view> || std::is_same_v<StringType, std::string>)
inline std::set<StringType> SplitToSet(std::string_view source, std::string_view sep, bool trim = true,
                                       bool clear = true)
{
    std::set<StringType> result;
    if (source.empty() || sep.empty()) {
        return result;
    }

    size_t posEnd = 0;
    size_t posStart = 0;
    do {
        posEnd = source.find(sep, posStart);
        if (posEnd == std::string_view::npos) {
            posEnd = source.length();
        }

        auto subStr = source.substr(posStart, posEnd - posStart);

        if (trim) {
            Trim(subStr);
        }

        if (!(clear && subStr.empty())) {
            result.emplace(subStr);
        }

        posStart = posEnd + sep.size();
    } while (posEnd < source.length());

    return result;
}

/**
 * @brief splicing set to string
 */
template <class StringType = std::string_view>
    requires(std::is_same_v<StringType, std::string_view> || std::is_same_v<StringType, std::string>)
inline std::string JoinSet(const std::set<StringType>& st, std::string_view sep)
{
    std::string result;
    for (auto itr = st.begin(); itr != st.end(); ++itr) {
        if (itr != st.begin()) {
            result += sep;
        }
        result += *itr;
    }
    return result;
}

/**
 * @brief comparison version, such as 6.1.1 6.2.8
 */
inline int CmpVersion(std::string_view ver1, std::string_view ver2)
{
    const auto& version1Detail = SplitToVec<std::string_view>(ver1, ".", true, true);
    const auto& version2Detail = SplitToVec<std::string_view>(ver2, ".", true, true);

    size_t idx = 0;
    for (idx = 0; idx < version1Detail.size() && idx < version2Detail.size(); ++idx) {
        int ver1Num = 0;
        int ver2Num = 0;
        auto [ptr1, ec1] = std::from_chars(version1Detail[idx].data(),
                                           version1Detail[idx].data() + version1Detail[idx].size(), ver1Num);
        auto [ptr2, ec2] = std::from_chars(version2Detail[idx].data(),
                                           version2Detail[idx].data() + version2Detail[idx].size(), ver2Num);
        if (ec1 != std::errc() || ec2 != std::errc() ||
            ptr1 != version1Detail[idx].data() + version1Detail[idx].size() ||
            ptr2 != version2Detail[idx].data() + version2Detail[idx].size()) {
            throw std::runtime_error("Invalid version format");
        }
        if (ver1Num < ver2Num) {
            return -1;
        }
        if (ver1Num > ver2Num) {
            return 1;
        }
    }
    if (idx == version1Detail.size() && idx == version2Detail.size()) {
        return 0;
    }
    return version1Detail.size() > version2Detail.size() ? 1 : -1;
}

/**
 * @brief Check whether the version is between the set versions
 */
inline bool CheckVersionInside(std::string_view ver, std::string_view startVer, std::string_view endVer)
{
    return (CmpVersion(ver, startVer.empty() ? "0.0.0.0" : startVer) >= 0 &&
            CmpVersion(ver, endVer.empty() ? "999.9.9.9" : endVer) <= 0);
}

namespace string_replace_detail {

/**
 * @brief Replace every match in place when the replacement is shorter (shift the tail left).
 */
inline void ReplaceShrinking(std::string& str, std::vector<size_t>& vecPos, std::string_view nv, size_t oldLen)
{
    const size_t vecLen = vecPos.size();
    const size_t newLen = nv.size();
    char* p = str.data() + vecPos[0];
    vecPos.emplace_back(str.size());
    for (size_t ii = 0; ii < vecLen; ++ii) {
        std::copy_n(nv.data(), newLen, p);
        p += newLen;
        size_t cplen = vecPos[ii + 1] - vecPos[ii] - oldLen;
        // Shift left: the destination starts before the source, so a forward copy is safe.
        std::copy_n(str.data() + vecPos[ii] + oldLen, cplen, p);
        p += cplen;
    }
    str.resize(static_cast<size_t>(p - str.data()));
}

/**
 * @brief Replace every match in place when the replacement is longer (grow, then shift from the back).
 */
inline void ReplaceGrowing(std::string& str, std::vector<size_t>& vecPos, std::string_view nv, size_t oldLen)
{
    const size_t vecLen = vecPos.size();
    const size_t newLen = nv.size();
    size_t diff = newLen - oldLen;
    vecPos.emplace_back(str.size());
    str.resize(str.size() + diff * vecLen);
    char* p = str.data() + str.size();
    for (size_t ii = vecLen - 1; ii < vecLen; --ii) {
        size_t cplen = vecPos[ii + 1] - vecPos[ii] - oldLen;
        p -= cplen;
        const char* src = str.data() + vecPos[ii] + oldLen;
        // Shift right: the destination ends after the source, so copy backwards.
        std::copy_backward(src, src + cplen, p + cplen);
        p -= newLen;
        std::copy_n(nv.data(), newLen, p);
    }
}

} // namespace string_replace_detail

/**
 * @brief Change the specified string ov in a string to the string nv
 */
inline std::string& ReplaceString(std::string& str, std::string_view ov, std::string_view nv)
{
    if (str.empty() || ov.empty()) {
        return str;
    }
    std::vector<size_t> vecPos;
    size_t pos = 0;
    size_t oldLen = ov.size();
    size_t newLen = nv.size();
    while ((pos = str.find(ov, pos)) != std::string::npos) {
        vecPos.emplace_back(pos);
        pos += oldLen;
    }
    const size_t vecLen = vecPos.size();
    if (vecLen == 0) {
        return str;
    }
    if (oldLen == newLen) {
        for (size_t ii = 0; ii < vecLen; ++ii) {
            std::copy_n(nv.data(), newLen, str.data() + vecPos[ii]);
        }
    } else if (oldLen > newLen) {
        string_replace_detail::ReplaceShrinking(str, vecPos, nv, oldLen);
    } else {
        string_replace_detail::ReplaceGrowing(str, vecPos, nv, oldLen);
    }
    return str;
}

/**
 * @brief determines whether a string is composed of numbers and letters
 */
inline bool IsAlnumStr(std::string_view str)
{
    if (str.length() == 0) {
        return false;
    }
    for (const auto& c : str) {
        if (!isalnum(static_cast<unsigned char>(c))) {
            return false;
        }
    }
    return true;
}

/**
 * @brief determines whether the string is composed of numbers
 */
inline bool IsDigitStr(std::string_view str)
{
    if (str.length() == 0) {
        return false;
    }
    for (const auto& c : str) {
        if (c > '9' || c < '0') {
            return false;
        }
    }
    return true;
}

/**
 * @brief Get the collection of keys in map
 */
template <typename KeyType, typename ValType>
inline std::set<KeyType> GetMapKeys(const std::map<KeyType, ValType>& m)
{
    std::set<KeyType> re;
    for (const auto& it : m) {
        re.emplace(it.first);
    }
    return re;
}

/**
 * @brief Replace the part of the string in the form of ${XXX_ENV} with the value of the corresponding environment
 * variable
 */
inline std::string ReplaceEnvVars(std::string_view input)
{
    // A linear scan instead of a std::regex built on every call (API-040).
    // Same rules as before: the name is everything up to the first '}', must
    // be non-empty, and inserted values are not expanded again.
    std::string result(input);
    size_t curPos = 0;
    while ((curPos = result.find("${", curPos)) != std::string::npos) {
        const size_t close = result.find('}', curPos + 2);
        if (close == std::string::npos) {
            break;
        }
        if (close == curPos + 2) { // "${}" is kept literally
            ++curPos;
            continue;
        }
        const std::string envName = result.substr(curPos + 2, close - curPos - 2);
        const char* envVal = std::getenv(envName.c_str());
        if (envVal == nullptr) {
            envVal = "";
        }
        result.replace(curPos, close + 1 - curPos, envVal);
        curPos += strlen(envVal);
    }
    return result;
}

// The <cctype> functions need the value as unsigned char: a UTF-8 byte is a
// negative char, which is undefined behavior for them.
inline char CharToLower(char c)
{
    return static_cast<char>(tolower(static_cast<unsigned char>(c)));
}
inline char CharToUpper(char c)
{
    return static_cast<char>(toupper(static_cast<unsigned char>(c)));
}

inline std::string& StrToLower(std::string& str)
{
    std::transform(str.begin(), str.end(), str.begin(), CharToLower);
    return str;
}

inline std::string StrToLower(std::string_view str)
{
    std::string result;
    result.resize(str.size());
    std::transform(str.begin(), str.end(), result.begin(), CharToLower);
    return result;
}

inline std::string& StrToUpper(std::string& str)
{
    std::transform(str.begin(), str.end(), str.begin(), CharToUpper);
    return str;
}

inline std::string StrToUpper(std::string_view str)
{
    std::string result;
    result.resize(str.size());
    std::transform(str.begin(), str.end(), result.begin(), CharToUpper);
    return result;
}

inline bool CheckIEqual(std::string_view str1, std::string_view str2)
{
    if (str1.size() != str2.size()) {
        return false;
    }
    return std::equal(str1.begin(), str1.end(), str2.begin(),
                      [](char a, char b) { return CharToLower(a) == CharToLower(b); });
}

inline std::string& StrToTitleCase(std::string& str)
{
    if (str.empty()) {
        return str;
    }
    std::string::iterator it = str.begin();
    *it = CharToUpper(*it);
    for (; it != str.end() - 1; ++it) {
        if (*it == ' ') {
            *(it + 1) = CharToUpper(*(it + 1));
        }
    }
    return str;
}

inline std::string& StandardisePath(std::string& path)
{
    if (path.empty()) {
        return (path = "/");
    }
    std::replace(path.begin(), path.end(), '\\', '/');
    if (path[path.length() - 1] != '/') {
        path += '/';
    }
    return path;
}

inline bool StartsWith(std::string_view str, std::string_view pattern, bool ignoreCase = false)
{
    const size_t strLen = str.length();
    const size_t patternLen = pattern.length();
    if (strLen < patternLen || patternLen == 0) {
        return false;
    }

    if (ignoreCase) {
        for (size_t i = 0; i < patternLen; ++i) {
            if (CharToLower(pattern[i]) != CharToLower(str[i])) {
                return false;
            }
        }
        return true;
    }
    for (size_t i = 0; i < patternLen; ++i) {
        if (pattern[i] != str[i]) {
            return false;
        }
    }
    return true;
}

inline bool EndsWith(std::string_view str, std::string_view pattern, bool ignoreCase = false)
{
    const size_t strLen = str.length();
    const size_t patternLen = pattern.length();
    if (strLen < patternLen || patternLen == 0) {
        return false;
    }

    const size_t& beginPos = strLen - patternLen;
    if (ignoreCase) {
        for (size_t i = 0; i < patternLen; ++i) {
            if (CharToLower(pattern[i]) != CharToLower(str[beginPos + i])) {
                return false;
            }
        }
        return true;
    }
    for (size_t i = 0; i < patternLen; i++) {
        if (pattern[i] != str[beginPos + i]) {
            return false;
        }
    }
    return true;
}

/**
 * @brief fnv1a hash algorithm, 64 bits
 */
inline uint64_t Hash64Fnv1a(const char* data, size_t len)
{
    constexpr uint64_t kPrime = 0x100000001b3;
    uint64_t hash = 0xcbf29ce484222325;
    for (size_t i = 0; i < len; ++i) {
        hash = (hash ^ static_cast<uint8_t>(data[i])) * kPrime;
    }
    return hash;
}

/**
 * @brief fnv1a hash algorithm, 32 bits
 */
inline uint32_t Hash32Fnv1a(const char* data, size_t len)
{
    constexpr uint32_t kPrime = 0x1000193;
    uint32_t hash = 0x811c9dc5;
    for (size_t i = 0; i < len; ++i) {
        hash = (hash ^ static_cast<uint8_t>(data[i])) * kPrime;
    }
    return hash;
}

template <typename T>
inline std::string SSToString(const T& obj)
{
    std::stringstream ss;
    ss << obj;
    return ss.str();
}

struct StringHash {
    using hash_type = std::hash<std::string_view>;
    using is_transparent = void;

    std::size_t operator()(const char* str) const { return hash_type{}(str); }
    std::size_t operator()(std::string_view str) const { return hash_type{}(str); }
    std::size_t operator()(const std::string& str) const { return hash_type{}(str); }
};

/**
 * @brief Safely calculates truncation position for UTF-8 string
 */
inline size_t SafeUtf8TruncationLength(const char* utf8Str, size_t actualLength, size_t desiredLength) noexcept
{
    if (desiredLength >= actualLength) {
        return actualLength;
    }

    size_t truncatePos = desiredLength;
    constexpr uint8_t contByteMask = 0xC0;
    constexpr uint8_t contByteFlag = 0x80;
    if ((utf8Str[truncatePos] & contByteMask) != contByteFlag) {
        return truncatePos;
    }

    while (truncatePos > 0 && ((utf8Str[truncatePos] & contByteMask) == contByteFlag)) {
        --truncatePos;
    }

    return truncatePos;
}

} // namespace ibmw::common::util

#include "base/string_kv_util.h"
#include "base/string_table_util.h"