/*
 * 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 <iomanip>
#include <sstream>
#include <string>
#include <string_view>
#include <type_traits>
#include <vector>

namespace ibmw::common::util {

namespace string_table_detail {

inline constexpr size_t CELL_PADDING = 2;
inline constexpr size_t KEY_VALUE_COLUMNS = 2;

/**
 * @brief Split a cell into its lines, dropping a trailing '\r' of each line and one trailing line break.
 */
inline std::vector<std::string_view> SplitCellLines(std::string_view sv)
{
    std::vector<std::string_view> result;
    size_t start = 0;
    for (size_t i = 0; i < sv.size(); ++i) {
        if (sv[i] != '\n') {
            continue;
        }
        size_t end = i;
        if (end > start && sv[end - 1] == '\r') {
            end--;
        }
        result.push_back(sv.substr(start, end - start));
        start = i + 1;
    }
    size_t end = sv.size();
    if (end > start && (sv[end - 1] == '\r' || sv[end - 1] == '\n')) {
        end--;
    }
    result.push_back(sv.substr(start, end - start));
    return result;
}

template <class StringType>
inline std::vector<size_t> BoxColumnWidths(const std::vector<std::vector<StringType>>& table)
{
    std::vector<size_t> columnWidth;
    for (const auto& rowItem : table) {
        if (columnWidth.size() < rowItem.size()) {
            columnWidth.resize(rowItem.size(), 0);
        }
        for (size_t ii = 0; ii < rowItem.size(); ++ii) {
            size_t maxLineWidthInCell = 0;
            for (const auto& line : SplitCellLines(rowItem[ii])) {
                maxLineWidthInCell = std::max(maxLineWidthInCell, line.size());
            }
            columnWidth[ii] = std::max(columnWidth[ii], maxLineWidthInCell);
        }
    }
    return columnWidth;
}

inline void DrawHorizontalLine(std::stringstream& result, const std::vector<size_t>& columnWidth)
{
    for (size_t jj = 0; jj < columnWidth.size(); ++jj) {
        result << "+" << std::setfill('-') << std::setw(columnWidth[jj]) << "-";
    }
    result << "+\n";
}

template <class StringType>
inline void DrawBoxRow(std::stringstream& result, const std::vector<StringType>& row,
                       const std::vector<size_t>& columnWidth)
{
    const size_t numColumns = columnWidth.size();
    size_t maxVisualLinesThisRow = 1;
    std::vector<std::vector<std::string_view>> splitCellsThisRow(numColumns);
    for (size_t jj = 0; jj < numColumns; ++jj) {
        if (row.size() > jj) {
            splitCellsThisRow[jj] = SplitCellLines(row[jj]);
            maxVisualLinesThisRow = std::max(maxVisualLinesThisRow, splitCellsThisRow[jj].size());
        } else {
            splitCellsThisRow[jj].push_back({});
        }
    }

    for (size_t lineIdx = 0; lineIdx < maxVisualLinesThisRow; ++lineIdx) {
        for (size_t jj = 0; jj < numColumns; ++jj) {
            std::string_view currentLineContent = (lineIdx < static_cast<size_t>(splitCellsThisRow[jj].size()))
                                                      ? splitCellsThisRow[jj][lineIdx]
                                                      : std::string_view{};

            std::string cellOutput = " ";
            cellOutput += currentLineContent;

            result << "|" << std::left << std::setfill(' ') << std::setw(columnWidth[jj]) << cellOutput;
        }
        result << "|\n";
    }
}

template <class StringType>
inline std::string FormatKeyValueTree(const std::vector<std::vector<StringType>>& table, std::string_view indent)
{
    std::ostringstream out;
    size_t maxKey = 0;
    for (const auto& row : table) {
        if (!row.empty()) {
            maxKey = std::max(maxKey, std::string_view(row[0]).size());
        }
    }
    for (const auto& row : table) {
        if (row.size() >= KEY_VALUE_COLUMNS) {
            out << indent << std::left << std::setw(static_cast<int>(maxKey + CELL_PADDING));
            out << std::string(row[0]) + ": " << row[1] << "\n";
        }
    }
    return out.str();
}

/**
 * @brief Width of each column, for multiline cells the longest line.
 */
template <class StringType>
inline std::vector<size_t> TreeColumnWidths(const std::vector<std::vector<StringType>>& table)
{
    size_t numCols = 0;
    for (const auto& row : table) {
        numCols = std::max(numCols, row.size());
    }
    std::vector<size_t> colWidths(numCols, 0);
    for (const auto& row : table) {
        for (size_t j = 0; j < row.size(); ++j) {
            std::string_view cell(row[j]);
            size_t maxLine = 0;
            size_t pos = 0;
            while (pos < cell.size()) {
                auto nl = cell.find('\n', pos);
                size_t len = (nl == std::string_view::npos) ? cell.size() - pos : nl - pos;
                maxLine = std::max(maxLine, len);
                pos += len + 1;
            }
            colWidths[j] = std::max(colWidths[j], maxLine);
        }
    }
    return colWidths;
}

inline void WriteTreeHeader(std::ostringstream& out, const std::vector<std::string_view>& headers,
                            const std::vector<size_t>& colWidths, std::string_view indent)
{
    out << indent;
    for (size_t j = 0; j < headers.size(); ++j) {
        out << std::left << std::setw(static_cast<int>(colWidths[j] + CELL_PADDING)) << headers[j];
    }
    out << "\n" << indent;
    for (size_t j = 0; j < headers.size(); ++j) {
        out << std::string(colWidths[j], '-');
        if (j + 1 < headers.size()) {
            out << "  ";
        }
    }
    out << "\n";
}

} // namespace string_table_detail

/**
 * @brief Draw a table
 */
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 DrawTable(const std::vector<std::vector<StringType>>& table, bool withHeader = true)
{
    size_t numLogicalRows = table.size();
    if (numLogicalRows == 0) {
        return "<empty table>";
    }

    std::vector<size_t> columnWidth = string_table_detail::BoxColumnWidths(table);
    if (columnWidth.empty() && numLogicalRows > 0) {
        return "<table with rows but no columns>";
    }

    for (auto& item : columnWidth) {
        item += string_table_detail::CELL_PADDING;
    }

    std::stringstream result;
    // first line
    string_table_detail::DrawHorizontalLine(result, columnWidth);

    for (size_t ii = 0; ii < numLogicalRows; ++ii) {
        string_table_detail::DrawBoxRow(result, table[ii], columnWidth);
        // table header
        if (withHeader && ii == 0) {
            string_table_detail::DrawHorizontalLine(result, columnWidth);
        }
    }

    // last line
    string_table_detail::DrawHorizontalLine(result, columnWidth);

    return result.str();
}

/**
 * @brief Render tabular data as an indented tree (no ASCII boxes).
 *
 * For a "key-value" table (2 columns, no header row, e.g. Base Info):
 *     key1 : val1
 *     key2 : val2
 *
 * For a multi-column table with a header row:
 *     - col0=val0  col1=val1  col2=val2
 *     - col0=val0  col1=val1  col2=val2
 *
 * @param table   2D string table. First row is the header when @p withHeader is true.
 * @param withHeader  If true, treat row 0 as column names.
 * @param indent  Prefix string for each line (default: 4 spaces).
 */
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 FormatTree(const std::vector<std::vector<StringType>>& table, bool withHeader = true,
                              std::string_view indent = "  ")
{
    if (table.empty()) {
        return std::string(indent) + "(none)\n";
    }

    // Key-value mode: 2 columns, no header
    if (!withHeader && !table.empty() && table[0].size() == string_table_detail::KEY_VALUE_COLUMNS) {
        return string_table_detail::FormatKeyValueTree(table, indent);
    }

    std::ostringstream out;
    // General table mode: compute column widths, render aligned columns
    size_t headerCount = withHeader ? 1 : 0;
    size_t dataStart = headerCount;

    std::vector<std::string_view> headers;
    if (withHeader && !table.empty()) {
        for (const auto& h : table[0]) {
            headers.emplace_back(h);
        }
    }

    if (table.size() <= dataStart) {
        out << indent << "(none)\n";
        return out.str();
    }

    // Compute max width per column (across header + data)
    std::vector<size_t> colWidths = string_table_detail::TreeColumnWidths(table);

    if (withHeader) {
        string_table_detail::WriteTreeHeader(out, headers, colWidths, indent);
    }

    // Print data rows
    for (size_t i = dataStart; i < table.size(); ++i) {
        const auto& row = table[i];
        out << indent;
        for (size_t j = 0; j < row.size(); ++j) {
            out << std::left << std::setw(static_cast<int>(colWidths[j] + string_table_detail::CELL_PADDING)) << row[j];
        }
        out << "\n";
    }

    return out.str();
}

} // namespace ibmw::common::util