#include "worktree/attributes.h"

#include <algorithm>
#include <cstring>

namespace vn {

namespace {

std::string_view trim(std::string_view text) {
    while (!text.empty() && (text.front() == ' ' || text.front() == '\t' || text.front() == '\r' ||
                             text.front() == '\n'))
        text.remove_prefix(1);
    while (!text.empty() && (text.back() == ' ' || text.back() == '\t' || text.back() == '\r' ||
                             text.back() == '\n'))
        text.remove_suffix(1);
    return text;
}

std::string_view next_token(std::string_view text, std::size_t& position) {
    while (position < text.size() && (text[position] == ' ' || text[position] == '\t'))
        ++position;
    const std::size_t start = position;
    while (position < text.size() && text[position] != ' ' && text[position] != '\t')
        ++position;
    return text.substr(start, position - start);
}

std::string_view basename(std::string_view path) {
    const auto slash = path.rfind('/');
    return slash == std::string_view::npos ? path : path.substr(slash + 1);
}

bool rule_matches(const std::string& pattern, bool has_slash, std::string_view path) {
    if (glob_match(pattern, path))
        return true;
    return !has_slash && glob_match(pattern, basename(path));
}

AttributeEol parse_eol(std::string_view value) {
    if (value == "lf")
        return AttributeEol::Lf;
    if (value == "crlf")
        return AttributeEol::Crlf;
    if (value == "cr")
        return AttributeEol::Cr;
    return AttributeEol::None;
}

} // namespace

AttributeRules AttributeRules::load(const fs::path& root) {
    AttributeRules rules;
    const fs::path path = root / ".vnattribs";
    if (const auto info = stat_path(path))
        rules.mtime_ns_ = static_cast<std::int64_t>(info->mtime_ns);
    const auto data = read_file_opt(path);
    if (!data)
        return rules;
    const std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());
    std::size_t start = 0;
    while (start <= text.size()) {
        const std::size_t end = text.find('\n', start);
        const std::size_t stop = end == std::string_view::npos ? text.size() : end;
        const std::string_view line = trim(text.substr(start, stop - start));
        start = stop == text.size() ? text.size() + 1 : stop + 1;
        if (line.empty() || line.front() == '#')
            continue;
        std::size_t position = 0;
        const std::string_view pattern = next_token(line, position);
        if (pattern.empty())
            continue;
        Rule rule;
        rule.pattern = std::string(pattern);
        rule.has_slash = pattern.find('/') != std::string_view::npos;
        while (position < line.size()) {
            const std::string_view token = next_token(line, position);
            if (token.empty())
                break;
            if (token == "gen") {
                rule.generated_set = true;
                rule.generated = true;
            } else if (token == "-gen") {
                rule.generated_set = true;
                rule.generated = false;
            } else if (token == "txt") {
                rule.text_set = true;
                rule.text = AttributeText::Text;
            } else if (token == "bin") {
                rule.text_set = true;
                rule.text = AttributeText::Binary;
            } else if (token == "-txt" || token == "-bin") {
                rule.text_set = true;
                rule.text = AttributeText::Auto;
            } else if (token == "-eol") {
                rule.eol_set = true;
                rule.eol = AttributeEol::None;
            } else if (token.starts_with("eol:")) {
                const auto value = token.substr(4);
                if (value == "lf" || value == "crlf" || value == "cr") {
                    rule.eol_set = true;
                    rule.eol = parse_eol(value);
                }
            }
        }
        rules.rules_.push_back(std::move(rule));
    }
    return rules;
}

PathAttributes AttributeRules::lookup(std::string_view path) const {
    PathAttributes result;
    for (const auto& rule : rules_) {
        if (!rule_matches(rule.pattern, rule.has_slash, path))
            continue;
        if (rule.generated_set)
            result.generated = rule.generated;
        if (rule.text_set)
            result.text = rule.text;
        if (rule.eol_set)
            result.eol = rule.eol;
    }
    return result;
}

bool AttributeRules::changed_since(std::int64_t cache_written_ms) const {
    if (cache_written_ms <= 0)
        return true;
    if (mtime_ns_ == 0)
        return false;
    return mtime_ns_ > cache_written_ms * 1'000'000;
}

std::vector<std::uint8_t> normalize_eol(Bytes data, AttributeEol eol) {
    std::vector<std::uint8_t> out;
    out.reserve(data.size());
    std::uint8_t first = '\n';
    std::uint8_t second = 0;
    switch (eol) {
    case AttributeEol::Lf:
        first = '\n';
        break;
    case AttributeEol::Crlf:
        first = '\r';
        second = '\n';
        break;
    case AttributeEol::Cr:
        first = '\r';
        break;
    case AttributeEol::None:
        out.insert(out.end(), data.begin(), data.end());
        return out;
    }
    for (std::size_t i = 0; i < data.size(); ++i) {
        const std::uint8_t byte = data[i];
        if (byte == '\r') {
            if (i + 1 < data.size() && data[i + 1] == '\n')
                ++i;
            out.push_back(first);
            if (second != 0)
                out.push_back(second);
        } else if (byte == '\n') {
            out.push_back(first);
            if (second != 0)
                out.push_back(second);
        } else {
            out.push_back(byte);
        }
    }
    return out;
}

} // namespace vn
