#include "test_support.h"

#include "cli.h"
#include "common.h"

#include <algorithm>
#include <array>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <map>
#include <set>
#include <sstream>
#include <string>
#include <string_view>
#include <vector>

#if !defined(_WIN32)
#include <sys/wait.h>
#endif

namespace vn {
namespace {

namespace fs = std::filesystem;

struct CommandResult {
    int code = 0;
    std::string out;
    std::string err;

    std::string text() const {
        return out + err;
    }
};

std::string trim_copy(std::string_view text) {
    std::size_t start = 0;
    std::size_t end = text.size();
    while (start < end && (text[start] == ' ' || text[start] == '\t' || text[start] == '\r' ||
                           text[start] == '\n'))
        ++start;
    while (end > start && (text[end - 1] == ' ' || text[end - 1] == '\t' || text[end - 1] == '\r' ||
                           text[end - 1] == '\n'))
        --end;
    return std::string(text.substr(start, end - start));
}

std::vector<std::string> split_lines(std::string_view text) {
    std::vector<std::string> lines;
    std::size_t start = 0;
    while (start < text.size()) {
        const std::size_t end = text.find('\n', start);
        if (end == std::string_view::npos) {
            lines.emplace_back(text.substr(start));
            break;
        }
        lines.emplace_back(text.substr(start, end - start));
        start = end + 1;
    }
    return lines;
}

std::vector<std::string> split_columns(std::string_view line) {
    std::vector<std::string> parts;
    std::size_t start = 0;
    while (start < line.size()) {
        while (start < line.size() && line[start] == ' ')
            ++start;
        if (start >= line.size())
            break;
        std::size_t end = start;
        while (end < line.size()) {
            if (line[end] == ' ' && end + 1 < line.size() && line[end + 1] == ' ')
                break;
            ++end;
        }
        parts.emplace_back(line.substr(start, end - start));
        start = end;
    }
    return parts;
}

std::string join_args(const std::vector<std::string>& args) {
    std::string out;
    for (std::size_t i = 0; i < args.size(); ++i) {
        if (i != 0)
            out.push_back(' ');
        out += args[i];
    }
    return out;
}

CommandResult run_cli(const std::vector<std::string>& command, const fs::path& cwd) {
    std::vector<std::string> args;
    args.reserve(command.size() + 1);
    args.emplace_back("vn");
    args.insert(args.end(), command.begin(), command.end());

    const fs::path previous = fs::current_path();
    fs::current_path(cwd);
    std::ostringstream out;
    std::ostringstream err;
    auto* old_out = std::cout.rdbuf(out.rdbuf());
    auto* old_err = std::cerr.rdbuf(err.rdbuf());
    int code = 0;
    try {
        code = cli_run(args);
    } catch (const std::exception& error) {
        code = 1;
        err << "exception: " << error.what() << "\n";
    } catch (...) {
        code = 1;
        err << "exception: unknown failure\n";
    }
    std::cout.flush();
    std::cerr.flush();
    std::cout.rdbuf(old_out);
    std::cerr.rdbuf(old_err);
    fs::current_path(previous);
    return CommandResult{code, out.str(), err.str()};
}

void set_environment(const char* key, const std::string& value) {
#if defined(_WIN32)
    _putenv_s(key, value.c_str());
#else
    setenv(key, value.c_str(), 1);
#endif
}

std::string shell_quote(std::string_view value) {
    std::string out = "'";
    for (char c : value) {
        if (c == '\'')
            out += "'\\''";
        else
            out.push_back(c);
    }
    out.push_back('\'');
    return out;
}

CommandResult run_shell(const std::vector<std::string>& command, const fs::path& cwd) {
#if defined(_WIN32)
    (void)command;
    (void)cwd;
    return CommandResult{1, {}, "shell commands are not supported on Windows\n"};
#else
    std::string line = "cd " + shell_quote(cwd.string()) + " && ";
    for (std::size_t i = 0; i < command.size(); ++i) {
        if (i != 0)
            line.push_back(' ');
        line += shell_quote(command[i]);
    }
    line += " 2>&1";
    FILE* pipe = popen(line.c_str(), "r");
    if (!pipe)
        return CommandResult{1, {}, "popen failed\n"};
    std::string out;
    std::array<char, 4096> buffer{};
    while (std::fgets(buffer.data(), static_cast<int>(buffer.size()), pipe) != nullptr)
        out += buffer.data();
    const int status = pclose(pipe);
    const int code = WIFEXITED(status) ? WEXITSTATUS(status) : 1;
    return CommandResult{code, out, {}};
#endif
}

struct LogRow {
    std::string commit;
    std::string message;
    std::string raw;
    bool working_copy = false;
};

struct VnFixture {
    fs::path root;
    fs::path home;
    fs::path repo;
    fs::path original_cwd;

    VnFixture() : original_cwd(fs::current_path()) {
        root = fs::temp_directory_path() /
               ("vn-test-" + std::to_string(random_u64()) + "-" +
                std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()));
        home = root / "home";
        repo = root / "repo";
        fs::create_directories(home / ".config");
        fs::create_directories(repo);
        set_environment("HOME", home.string());
        set_environment("XDG_CONFIG_HOME", (home / ".config").string());
        set_environment("USER", "tester");
        set_environment("GIT_AUTHOR_NAME", "Tester");
        set_environment("GIT_AUTHOR_EMAIL", "tester@example.com");
        set_environment("GIT_COMMITTER_NAME", "Tester");
        set_environment("GIT_COMMITTER_EMAIL", "tester@example.com");
        set_environment("NO_COLOR", "1");
        set_environment("TZ", "UTC");
        set_environment("VN_EDITOR", "/bin/true");
    }

    ~VnFixture() {
        std::error_code ec;
        fs::current_path(original_cwd, ec);
        fs::remove_all(root, ec);
    }

    CommandResult vn(const std::vector<std::string>& command, const fs::path& cwd = {},
                     bool check = true,
                     const std::source_location& location = std::source_location::current()) const {
        const fs::path actual_cwd = cwd.empty() ? repo : cwd;
        CommandResult result = run_cli(command, actual_cwd);
        if (check && result.code != 0) {
            throw test::Failure(test::location_text(location) +
                                ": command failed: " + join_args(command) + "\nstdout:\n" +
                                result.out + "\nstderr:\n" + result.err);
        }
        return result;
    }

    CommandResult
    failed(const std::vector<std::string>& command, std::string_view expected = {},
           const fs::path& cwd = {},
           const std::source_location& location = std::source_location::current()) const {
        CommandResult result = vn(command, cwd, false, location);
        if (result.code == 0) {
            throw test::Failure(test::location_text(location) + ": command unexpectedly passed: " +
                                join_args(command) + "\n" + result.text());
        }
        if (!expected.empty() && result.text().find(expected) == std::string::npos) {
            throw test::Failure(test::location_text(location) + ": expected output to contain \"" +
                                std::string(expected) + "\"\n" + result.text());
        }
        return result;
    }

    void init(const fs::path& cwd = {}) {
        vn({"init", "."}, cwd);
    }

    void write(const fs::path& relative, std::string_view content, const fs::path& cwd = {}) const {
        const fs::path path = (cwd.empty() ? repo : cwd) / relative;
        fs::create_directories(path.parent_path());
        const Bytes bytes(reinterpret_cast<const std::uint8_t*>(content.data()), content.size());
        if (!write_file(path, bytes))
            throw test::Failure("cannot write test file: " + path.string());
    }

    std::string read(const fs::path& relative, const fs::path& cwd = {}) const {
        const fs::path path = (cwd.empty() ? repo : cwd) / relative;
        const auto data = read_file_opt(path);
        if (!data)
            throw test::Failure("cannot read test file: " + path.string());
        return std::string(reinterpret_cast<const char*>(data->data()), data->size());
    }

    bool exists(const fs::path& relative, const fs::path& cwd = {}) const {
        return path_exists((cwd.empty() ? repo : cwd) / relative);
    }

    void commit(std::string_view message, const fs::path& cwd = {}) const {
        vn({"go", "-m", std::string(message)}, cwd);
    }

    std::string hash(std::string_view revision = "@", const fs::path& cwd = {}) const {
        return trim_copy(vn({"hash", std::string(revision)}, cwd).out);
    }

    std::string short_hash(std::string_view revision = "@", const fs::path& cwd = {}) const {
        return trim_copy(vn({"hash", "-short", std::string(revision)}, cwd).out);
    }

    std::vector<LogRow> log_rows(const fs::path& cwd = {}) const {
        const std::string output = vn({"log", "-no-col-titles"}, cwd).out;
        std::vector<LogRow> rows;
        for (const std::string& line : split_lines(output)) {
            const std::string stripped = trim_copy(line);
            if (stripped.empty())
                continue;
            std::vector<std::string> parts = split_columns(stripped);
            if (parts.empty())
                continue;
            LogRow row;
            row.raw = line;
            row.working_copy = parts[0].starts_with("@");
            std::string first = row.working_copy ? trim_copy(parts[0].substr(1)) : parts[0];
            row.commit = first.substr(0, std::min<std::size_t>(12, first.size()));
            row.message = parts.size() > 1 ? parts.back() : std::string();
            rows.push_back(std::move(row));
        }
        return rows;
    }

    std::vector<std::string> log_commits(const fs::path& cwd = {}) const {
        std::vector<std::string> commits;
        for (const LogRow& row : log_rows(cwd))
            commits.push_back(row.commit);
        return commits;
    }

    std::string commit_for_message(std::string_view message, const fs::path& cwd = {}) const {
        for (const LogRow& row : log_rows(cwd)) {
            if (row.message.find(message) != std::string::npos)
                return row.commit;
        }
        throw test::Failure("no commit with message \"" + std::string(message) + "\"");
    }

    std::map<std::string, std::string> metadata(std::string_view revision = "@",
                                                const fs::path& cwd = {}) const {
        const std::string output = vn({"show", std::string(revision)}, cwd).out;
        std::map<std::string, std::string> values;
        for (const std::string& line : split_lines(output)) {
            if (line.empty())
                break;
            const std::size_t space = line.find(' ');
            if (space == std::string::npos)
                continue;
            const std::string key = line.substr(0, space);
            if (key == "commit" || key == "change" || key == "author" || key == "date" ||
                key == "parents") {
                values[key] = trim_copy(line.substr(space + 1));
            }
        }
        return values;
    }

    std::set<std::string> parents(std::string_view revision = "@", const fs::path& cwd = {}) const {
        std::set<std::string> result;
        const auto values = metadata(revision, cwd);
        const auto found = values.find("parents");
        if (found == values.end())
            return result;
        std::istringstream stream(found->second);
        std::string parent;
        while (stream >> parent)
            result.insert(parent);
        return result;
    }
};

bool git_available() {
    return run_shell({"git", "--version"}, fs::current_path()).code == 0;
}

void require_shell(test::Context& t, const CommandResult& result, std::string_view label) {
    if (result.code != 0)
        t.fail(std::string(label) + " failed:\n" + result.text());
}

fs::path make_git_repository(test::Context& t, VnFixture& f) {
    const fs::path git_repo = f.root / "gitrepo";
    fs::create_directories(git_repo);
    require_shell(t, run_shell({"git", "init", "-q"}, git_repo), "git init");
    require_shell(t, run_shell({"git", "config", "user.name", "Git Tester"}, git_repo),
                  "git config user.name");
    require_shell(t, run_shell({"git", "config", "user.email", "git@example.com"}, git_repo),
                  "git config user.email");
    f.write("a.txt", "one\n", git_repo);
    require_shell(t, run_shell({"git", "add", "a.txt"}, git_repo), "git add");
    require_shell(t, run_shell({"git", "commit", "-qm", "git one"}, git_repo), "git commit one");
    f.write("a.txt", "one\ntwo\n", git_repo);
    require_shell(t, run_shell({"git", "commit", "-qam", "git two"}, git_repo), "git commit two");
    return git_repo;
}

void linear_history(VnFixture& f, int count) {
    for (int index = 0; index < count; ++index) {
        f.write("file.txt", "line " + std::to_string(index) + "\n");
        f.commit("commit " + std::to_string(index));
    }
}

void core_init_version_help(test::Context& t) {
    VnFixture f;
    f.init();
    t.expect(fs::exists(f.repo / ".veins" / "format"));
    t.expect(fs::is_directory(f.repo / ".veins" / "op-heads"));
    t.expect_contains(f.vn({"version"}).out, "veins");
    const std::string help_text = f.vn({"help"}).out;
    t.expect_contains(help_text, "subcommands:");
    t.expect_contains(f.vn({"help", "log"}).out, "vn log");
    t.expect_contains(f.vn({"help", "go"}).out, "aliases: commit");
}

void core_outside_repository(test::Context& t) {
    VnFixture f;
    const fs::path outside = f.root / "outside";
    fs::create_directories(outside);
    for (const std::vector<std::string>& command :
         std::vector<std::vector<std::string>>{{"stat"}, {"log"}, {"hash"}, {"ls"}}) {
        f.failed(command, "not a veins repository", outside);
    }
    t.expect_contains(f.vn({"version"}, outside).out, "veins");
}

void core_status_list_diff_describe(test::Context& t) {
    VnFixture f;
    f.init();
    f.write("a.txt", "alpha\n");
    f.write("dir/b.txt", "beta\n");
    const std::string status = f.vn({"stat"}).out;
    t.expect_contains(status, "A a.txt");
    t.expect_contains(status, "A dir/b.txt");
    std::vector<std::string> plain = split_lines(f.vn({"ls", "-plain"}).out);
    plain.erase(std::remove(plain.begin(), plain.end(), ""), plain.end());
    std::sort(plain.begin(), plain.end());
    t.expect_eq(plain.size(), 2u);
    if (plain.size() == 2) {
        t.expect_eq(plain[0], "a.txt");
        t.expect_eq(plain[1], "dir/b.txt");
    }
    const std::string listed = f.vn({"ls"}).out;
    t.expect_contains(listed, "a.txt");
    t.expect_contains(listed, "b.txt");
    const std::string diff = f.vn({"diff"}).out;
    t.expect_contains(diff, "+alpha");
    t.expect_contains(diff, "+beta");
    f.vn({"desc", "-m", "draft message"});
    t.expect_contains(f.vn({"show", "@"}).out, "draft message");
    t.expect_contains(f.vn({"stat"}).out, "A a.txt");
}

void core_commit_log_show_hash(test::Context& t) {
    VnFixture f;
    f.init();
    f.write("a.txt", "one\n");
    f.commit("first commit");
    t.expect_contains(f.vn({"stat"}).out, "working copy clean");
    const std::vector<LogRow> rows = f.log_rows();
    t.expect(rows.size() >= 2);
    if (!rows.empty())
        t.expect(rows.front().working_copy);
    const std::string first = f.commit_for_message("first commit");
    const auto info = f.metadata(first);
    t.expect_eq(info.at("commit").size(), 64u);
    t.expect_eq(f.short_hash(first), info.at("commit").substr(0, 12));
    t.expect_eq(f.hash(first), info.at("commit"));
    const std::string shown = f.vn({"show", first}).out;
    t.expect_contains(shown, "first commit");
    t.expect_contains(shown, "+one");
    t.expect_contains(f.vn({"show", "-no-col-titles", first}).out, "--- /dev/null");

    f.write("a.txt", "two\n");
    t.expect_contains(f.vn({"stat"}).out, "M a.txt");
    t.expect_contains(f.vn({"diff"}).out, "+two");
    f.commit("second commit");
    t.expect_contains(f.vn({"show", f.commit_for_message("second commit")}).out, "second commit");
    t.expect_contains(f.vn({"stat"}).out, "working copy clean");
}

void core_log_limits_revisions(test::Context& t) {
    VnFixture f;
    f.init();
    linear_history(f, 4);
    const std::vector<LogRow> full = f.log_rows();
    t.expect_eq(full.size(), 5u);
    t.expect_eq(split_lines(f.vn({"log", "-l2", "-no-col-titles"}).out).size(), 2u);
    const auto oldest = split_lines(f.vn({"log", "-f2", "-no-col-titles"}).out);
    t.expect_eq(oldest.size(), 2u);
    if (oldest.size() == 2) {
        t.expect_contains(oldest[0], "commit 0");
        t.expect_contains(oldest[1], "commit 1");
    }
    t.expect_eq(split_lines(f.vn({"log", "-l", "1", "-no-col-titles"}).out).size(), 1u);
    t.expect_eq(split_lines(f.vn({"log", "l2", "-no-col-titles"}).out).size(), 2u);
    const std::string one = f.commit_for_message("commit 1");
    const std::string selected = f.vn({"log", "-rev", one, "-no-col-titles"}).out;
    t.expect_contains(selected, "commit 1");
    t.expect_contains(selected, "commit 0");
    t.expect_not_contains(selected, "commit 2");
    for (const char* bad : {"-l0", "-lfoo", "-bad"})
        f.failed({"log", bad});
}

void core_checkout_materializes_and_new(test::Context& t) {
    VnFixture f;
    f.init();
    f.write("a.txt", "one\n");
    f.vn({"bmk", "set", "main"});
    f.commit("first");
    const std::string first = f.hash("main");
    f.write("a.txt", "two\n");
    f.write("later.txt", "later\n");
    f.commit("second");
    const std::string second = f.hash("main");
    f.vn({"bmk", "set", "main", "-rev", first});
    f.vn({"bmk", "set", "feature", "-rev", second});

    f.vn({"co", "main"});
    t.expect_eq(f.read("a.txt"), "one\n");
    t.expect(!f.exists("later.txt"));
    t.expect_contains(f.vn({"stat"}).out, "working copy clean");
    t.expect_contains(f.vn({"bmk", "ls"}).out, "main");

    f.vn({"co", "feature"});
    t.expect_eq(f.read("a.txt"), "two\n");
    t.expect(f.exists("later.txt"));

    f.vn({"co", second});
    t.expect_eq(f.read("a.txt"), "two\n");
    f.vn({"new"});
    t.expect_contains(f.vn({"stat"}).out, "working copy clean");
    t.expect(!f.log_rows().empty());
    if (!f.log_rows().empty())
        t.expect(f.log_rows().front().working_copy);
}

void worktree_rename_and_delete(test::Context& t) {
    VnFixture f;
    f.init();
    f.write("a.txt", "alpha\n");
    f.write("b.txt", "beta\n");
    f.commit("base");
    f.vn({"mv", "a.txt", "renamed.txt"});
    t.expect(!f.exists("a.txt"));
    t.expect_eq(f.read("renamed.txt"), "alpha\n");
    const std::string status = f.vn({"stat"}).out;
    t.expect_contains(status, "D a.txt");
    t.expect_contains(status, "A renamed.txt");
    f.commit("rename");
    t.expect_contains(f.vn({"ls", "-plain"}).out, "renamed.txt");

    fs::remove(f.repo / "b.txt");
    t.expect_contains(f.vn({"stat"}).out, "D b.txt");
    f.commit("delete");
    t.expect_not_contains(f.vn({"ls", "-plain"}).out, "b.txt");
}

void worktree_exclude_and_remove(test::Context& t) {
    VnFixture f;
    f.init();
    f.write("src/a.c", "a\n");
    f.write("src/b.c", "b\n");
    f.write("docs/readme.md", "docs\n");
    f.write("top.txt", "top\n");
    t.expect_contains(f.vn({"rm", "src/*.c"}).out, "will be re-added");
    f.vn({"ex", "src/*.c"});
    t.expect_contains(f.read(".vnexclude"), "src/*.c");
    const std::string tracked = f.vn({"ls", "-plain"}).out;
    t.expect_not_contains(tracked, "src/a.c");
    t.expect_not_contains(tracked, "src/b.c");
    t.expect(f.exists("src/a.c"));
    t.expect(f.exists("src/b.c"));
    f.vn({"rm", "-delete", "docs/readme.md"});
    t.expect(!f.exists("docs/readme.md"));
    t.expect_not_contains(f.vn({"ls", "-plain"}).out, "docs/readme.md");
    t.expect_contains(f.vn({"ex", "src/*.c"}).out, "no new exclude rules");
    f.failed({"rm", "missing.txt"}, "not tracked");
}

void worktree_ignore_rules(test::Context& t) {
    VnFixture f;
    f.init();
    f.write(".gitignore", "*.log\nbuild/\n");
    f.write("debug.log", "ignored\n");
    f.write("build/out.bin", "ignored\n");
    f.write("src/.gitignore", "*.tmp\n");
    f.write("src/notes.tmp", "ignored\n");
    f.write("src/main.c", "kept\n");
    std::vector<std::string> tracked = split_lines(f.vn({"ls", "-plain"}).out);
    tracked.erase(std::remove(tracked.begin(), tracked.end(), ""), tracked.end());
    std::sort(tracked.begin(), tracked.end());
    t.expect_eq(tracked.size(), 3u);
    if (tracked.size() == 3) {
        t.expect_eq(tracked[0], ".gitignore");
        t.expect_eq(tracked[1], "src/.gitignore");
        t.expect_eq(tracked[2], "src/main.c");
    }
    f.write("root.log", "ignored\n");
    t.expect_not_contains(f.vn({"stat"}).out, "root.log");
}

void worktree_checkout_removes_later_files(test::Context& t) {
    VnFixture f;
    f.init();
    f.write("keep.txt", "keep\n");
    f.commit("first");
    const std::string first = f.commit_for_message("first");
    f.write("later.txt", "later\n");
    f.write("keep.txt", "changed\n");
    f.commit("second");
    f.vn({"co", first});
    t.expect(f.exists("keep.txt"));
    t.expect(!f.exists("later.txt"));
    t.expect_eq(f.read("keep.txt"), "keep\n");
    t.expect_contains(f.vn({"stat"}).out, "working copy clean");
}

void worktree_editor(test::Context& t) {
#if defined(_WIN32)
    t.expect(true);
#else
    VnFixture f;
    f.init();
    const fs::path editor = f.root / "editor.sh";
    f.write("editor.sh", "#!/bin/sh\nprintf \"edited:%s\\n\" \"$1\" > \"$1\"\n", f.root);
    fs::permissions(editor, fs::perms::owner_exec | fs::perms::owner_read | fs::perms::owner_write,
                    fs::perm_options::add);
    f.vn({"cfg", "editor", editor.string()});
    f.write("target.txt", "before\n");
    f.vn({"edit", "target.txt"});
    t.expect_eq(f.read("target.txt"), "edited:target.txt\n");
    f.vn({"cfg", "-unset", "editor"});
#endif
}

void history_log_is_topological(test::Context& t) {
    VnFixture f;
    f.init();
    f.write("base.txt", "base\n");
    f.vn({"bmk", "set", "master"});
    f.commit("base");
    f.vn({"bmk", "set", "left"});
    f.vn({"new", "left"});
    f.write("left.txt", "left\n");
    f.commit("left");
    f.vn({"bmk", "set", "right"});
    f.vn({"new", "master"});
    f.write("right.txt", "right\n");
    f.commit("right");

    const std::vector<std::string> commits = f.log_commits();
    for (std::size_t index = 0; index < commits.size(); ++index) {
        for (const std::string& parent : f.parents(commits[index])) {
            const auto found = std::find(commits.begin(), commits.end(), parent.substr(0, 12));
            if (found == commits.end())
                continue;
            const std::size_t parent_index =
                static_cast<std::size_t>(std::distance(commits.begin(), found));
            t.expect(parent_index > index);
        }
    }
}

void history_amend_rewrites_descendants(test::Context& t) {
    VnFixture f;
    f.init();
    f.write("f.txt", "one\n");
    f.commit("one");
    const std::string one = f.commit_for_message("one");
    f.write("f.txt", "two\n");
    f.commit("two");
    const std::string two = f.commit_for_message("two");
    const std::string one_change = f.metadata(one).at("change");
    const std::string two_change = f.metadata(two).at("change");
    f.vn({"amend", one, "-m", "one renamed"});
    const std::string new_one = f.commit_for_message("one renamed");
    const std::string new_two = f.commit_for_message("two");
    t.expect_ne(one.substr(0, 12), new_one);
    t.expect_ne(two.substr(0, 12), new_two);
    t.expect_eq(f.metadata(new_one).at("change"), one_change);
    t.expect_eq(f.metadata(new_two).at("change"), two_change);
    t.expect_eq(f.parents(new_two).count(new_one), 1u);
}

void history_undo_and_operation_restore(test::Context& t) {
    VnFixture f;
    f.init();
    f.write("f.txt", "one\n");
    f.commit("one");
    const std::string one = f.commit_for_message("one");
    f.write("f.txt", "two\n");
    f.commit("two");
    f.vn({"amend", one, "-m", "renamed"});
    t.expect_contains(f.vn({"log"}).out, "renamed");
    f.vn({"undo"});
    t.expect_not_contains(f.vn({"log"}).out, "renamed");
    const std::vector<std::string> ops = split_lines(f.vn({"op", "log"}).out);
    t.expect(ops.size() >= 2);
    if (ops.size() >= 2) {
        std::istringstream stream(ops[1]);
        std::string previous;
        stream >> previous;
        f.vn({"op", "restore", previous});
        t.expect_contains(f.vn({"log"}).out, "renamed");
    }
}

void history_diff_path_filter(test::Context& t) {
    VnFixture f;
    f.init();
    f.write("one.txt", "one\n");
    f.write("two.txt", "two\n");
    f.commit("base");
    f.write("one.txt", "one changed\n");
    f.write("two.txt", "two changed\n");

    const std::string one_diff = f.vn({"diff", "one.txt"}).out;
    t.expect_contains(one_diff, "+one changed");
    t.expect_not_contains(one_diff, "+two changed");
    const std::string all_diff = f.vn({"diff", "-a"}).out;
    t.expect_contains(all_diff, "+one changed");
    t.expect_contains(all_diff, "+two changed");

    const fs::path subdir = f.repo / "sub";
    fs::create_directories(subdir);
    const std::string relative_diff = f.vn({"diff", "../one.txt"}, subdir).out;
    t.expect_contains(relative_diff, "+one changed");
    t.expect_not_contains(relative_diff, "+two changed");

    f.vn({"go", "-m", "second"});
    const std::string second = f.commit_for_message("second");
    const std::string revision_diff = f.vn({"diff", "-rev", second, "one.txt"}).out;
    t.expect_contains(revision_diff, "+one changed");
    t.expect_not_contains(revision_diff, "+two changed");
    t.expect_contains(f.vn({"diff"}).out, "no diff to show");
    t.expect_contains(f.vn({"help", "diff"}).out, "-a, -all");
}

void history_show_and_diff(test::Context& t) {
    VnFixture f;
    f.init();
    f.write("f.txt", "one\n");
    f.commit("one");
    const std::string one = f.commit_for_message("one");
    f.write("f.txt", "two\n");
    f.commit("two");
    const std::string diff = f.vn({"diff", one, "@"}).out;
    t.expect_contains(diff, "-one");
    t.expect_contains(diff, "+two");
    t.expect_contains(f.vn({"show", one}).out, "one");
}

void refs_bookmarks(test::Context& t) {
    VnFixture f;
    f.init();
    f.write("f.txt", "one\n");
    f.commit("one");
    const std::string one = f.commit_for_message("one");
    f.write("f.txt", "two\n");
    f.commit("two");
    const std::string two = f.commit_for_message("two");
    f.vn({"bmk", "set", "main", "-rev", one});
    f.vn({"bmk", "set", "feature", "-rev", two});
    std::string listing = f.vn({"bmk", "ls"}).out;
    t.expect_contains(listing, "main");
    t.expect_contains(listing, "feature");
    f.vn({"bmk", "mv", "main", "-rev", two});
    t.expect_contains(f.vn({"bmk", "ls"}).out, two.substr(0, 12));
    f.vn({"bmk", "rm", "feature"});
    t.expect_not_contains(f.vn({"bmk", "ls"}).out, "feature");
    f.failed({"bmk", "rm", "missing"}, "no such bookmark");
}

void refs_current_bookmark(test::Context& t) {
    VnFixture f;
    f.init();
    f.write("f.txt", "one\n");
    f.vn({"bmk", "set", "main"});
    f.commit("one");
    const std::string one = f.hash("main");
    t.expect_contains(f.vn({"bmk", "ls"}).out, one.substr(0, 12));
    f.write("f.txt", "two\n");
    f.commit("two");
    const std::string two = f.hash("main");
    t.expect_ne(one, two);
    t.expect_contains(f.vn({"bmk", "ls"}).out, two.substr(0, 12));
    t.expect_contains(f.vn({"cfg"}).out, "bookmark.current = main");
}

void refs_tags(test::Context& t) {
    VnFixture f;
    f.init();
    f.write("f.txt", "one\n");
    f.commit("one");
    f.vn({"tag", "set", "v0.0.9"});
    f.vn({"tag", "set", "v0.0.10"});
    const std::string listing = f.vn({"tag", "ls"}).out;
    t.expect_contains(listing, "v0.0.9");
    t.expect_contains(listing, "v0.0.10");
    t.expect_eq(trim_copy(f.vn({"tag", "latest"}).out), "v0.0.10");
    f.vn({"tag", "rm", "v0.0.9"});
    t.expect_not_contains(f.vn({"tag", "ls"}).out, "v0.0.9");
    f.failed({"tag", "rm", "missing"}, "no such tag");
}

void refs_remote_configuration(test::Context& t) {
    VnFixture f;
    f.init();
    f.vn({"remote", "add", "origin", "file:///tmp/example"});
    t.expect_contains(f.vn({"remote", "list"}).out, "origin");
    f.failed({"remote", "add", "origin", "file:///other"}, "already exists");
    f.vn({"remote", "set-url", "origin", "file:///tmp/other"});
    t.expect_contains(f.vn({"remote", "list"}).out, "file:///tmp/other");
    f.vn({"remote", "remove", "origin"});
    t.expect_not_contains(f.vn({"remote", "list"}).out, "origin");
    f.failed({"remote", "remove", "origin"}, "unknown remote");
}

void config_local(test::Context& t) {
    VnFixture f;
    f.init();
    f.vn({"cfg", "test.key", "value"});
    t.expect_eq(trim_copy(f.vn({"cfg", "test.key"}).out), "value");
    t.expect_contains(f.vn({"cfg"}).out, "test.key = value");
    f.vn({"cfg", "set", "test.other", "two"});
    t.expect_eq(trim_copy(f.vn({"cfg", "get", "test.other"}).out), "two");
    f.vn({"cfg", "-unset", "test.key"});
    f.failed({"cfg", "test.key"}, "unknown config key");
    f.vn({"cfg", "unset", "test.other"});
    f.failed({"cfg", "test.other"}, "unknown config key");
}

void config_global_identity(test::Context& t) {
    VnFixture f;
    f.init();
    f.vn({"cfg", "-global", "user.name", "Global Tester"});
    f.vn({"cfg", "-global", "user.email", "global@example.com"});
    t.expect_eq(trim_copy(f.vn({"cfg", "-global", "user.name"}).out), "Global Tester");
    f.write("f.txt", "content\n");
    f.commit("global identity");
    t.expect_contains(f.vn({"show", f.commit_for_message("global identity")}).out, "Global Tester");
    t.expect(fs::exists(f.home / ".local" / "config" / "veins" / "veins.toml"));
}

void config_errors(test::Context& t) {
    (void)t;
    VnFixture f;
    f.init();
    f.failed({"cfg", "key", "value", "extra"}, "accepts a key and one value");
    f.failed({"cfg", "-unset"}, "requires one key");
    f.failed({"cfg", "unknown"}, "unknown config key");
}

void config_pager(test::Context& t) {
    VnFixture f;
    f.init();
    f.vn({"cfg", "pager", "cat"});
    t.expect_eq(pager_command(f.repo), "cat");
    f.vn({"cfg", "-global", "pager", "more"});
    t.expect_eq(pager_command(f.repo), "more");
}

void create_diverged(VnFixture& f, bool same_file) {
    f.init();
    f.write("f.txt", "base\n");
    f.vn({"bmk", "set", "master"});
    f.commit("base");
    f.vn({"bmk", "set", "left"});
    f.vn({"new", "left"});
    f.write("f.txt", same_file ? "left\n" : "base\n");
    f.write("left.txt", "left\n");
    f.commit("left");
    f.vn({"bmk", "set", "right"});
    f.vn({"new", "master"});
    f.write("f.txt", same_file ? "right\n" : "base\n");
    f.write("right.txt", "right\n");
    f.commit("right");
}

void merge_clean(test::Context& t) {
    VnFixture f;
    create_diverged(f, false);
    f.vn({"merge", "left"});
    t.expect(f.metadata("@").at("parents").find(' ') != std::string::npos);
    t.expect(f.exists("left.txt"));
    t.expect(f.exists("right.txt"));
    f.commit("merge");
    t.expect_contains(f.vn({"log"}).out, "merge");
    t.expect_contains(f.vn({"xs"}).out, "no conflicts");
    t.expect_contains(f.vn({"fsck"}).out, "fsck: clean");
}

void merge_conflict_resolve_theirs(test::Context& t) {
    VnFixture f;
    create_diverged(f, true);
    f.vn({"merge", "left"});
    const std::string status = f.vn({"stat"}).out;
    t.expect_contains(status, "C f.txt");
    t.expect_contains(status, "1 conflict(s)");
    t.expect_contains(status, "1 conflicted commit(s) in ancestry");
    t.expect(f.exists("f.txt.base"));
    t.expect(f.exists("f.txt.ours"));
    t.expect(f.exists("f.txt.theirs"));
    t.expect_contains(f.vn({"xs", "-porcelain"}).out, "f.txt\ttext\t");
    t.expect_contains(f.vn({"show", "@"}).out, "f.txt");
    f.vn({"resolve", "-take", "theirs", "f.txt"});
    t.expect_contains(f.vn({"stat"}).out, "M f.txt");
    t.expect_eq(f.read("f.txt"), "left\n");
    t.expect_contains(f.vn({"xs"}).out, "no conflicts");
    f.commit("resolved");
    t.expect_contains(f.vn({"stat"}).out, "working copy clean");
}

void merge_conflict_resolve_ours(test::Context& t) {
    VnFixture f;
    create_diverged(f, true);
    f.vn({"merge", "left"});
    f.vn({"resolve", "-take", "ours", "f.txt"});
    t.expect_eq(f.read("f.txt"), "right\n");
    t.expect_contains(f.vn({"xs"}).out, "no conflicts");
}

void merge_conflict_resolve_current(test::Context& t) {
    VnFixture f;
    create_diverged(f, true);
    f.vn({"merge", "left"});
    f.write("f.txt", "manual resolution\n");
    f.vn({"resolve", "f.txt"});
    t.expect_eq(f.read("f.txt"), "manual resolution\n");
    t.expect_contains(f.vn({"xs"}).out, "no conflicts");
}

void merge_multiple(test::Context& t) {
    VnFixture f;
    create_diverged(f, false);
    f.vn({"merge", "left", "right"});
    std::istringstream parents(f.metadata("@").at("parents"));
    std::size_t count = 0;
    std::string parent;
    while (parents >> parent)
        ++count;
    t.expect_eq(count, 3u);
}

void rebase_changes_parent(test::Context& t) {
    VnFixture f;
    f.init();
    f.write("base.txt", "base\n");
    f.vn({"bmk", "set", "master"});
    f.commit("base");
    f.vn({"bmk", "set", "left"});
    f.vn({"new", "left"});
    f.write("left.txt", "left\n");
    f.commit("left");
    const std::string left_change = f.metadata("left").at("change");
    f.vn({"bmk", "set", "right"});
    f.vn({"new", "master"});
    f.write("right.txt", "right\n");
    f.commit("right");
    const std::string right = f.hash("right");
    f.vn({"rebase", "-s", "left", "-d", "right"});
    t.expect_eq(f.parents("left").count(right.substr(0, 12)), 1u);
    t.expect_eq(f.metadata("left").at("change"), left_change);
    t.expect_contains(f.vn({"show", "left"}).out, "left");
}

void rebase_rewrites_descendants(test::Context& t) {
    VnFixture f;
    f.init();
    f.write("base.txt", "base\n");
    f.vn({"bmk", "set", "master"});
    f.commit("base");
    f.vn({"bmk", "set", "side"});
    f.vn({"new", "side"});
    f.write("one.txt", "one\n");
    f.commit("one");
    const std::string first = f.commit_for_message("one");
    const std::string first_change = f.metadata(first).at("change");
    f.write("two.txt", "two\n");
    f.commit("two");
    const std::string second = f.commit_for_message("two");
    const std::string second_change = f.metadata(second).at("change");
    f.vn({"bmk", "set", "target"});
    f.vn({"new", "master"});
    f.write("target.txt", "target\n");
    f.commit("target");
    const std::string target = f.commit_for_message("target");
    f.vn({"rebase", "-s", first, "-d", target});
    const std::string new_first = f.commit_for_message("one");
    const std::string new_second = f.commit_for_message("two");
    t.expect_eq(f.metadata(new_first).at("change"), first_change);
    t.expect_eq(f.metadata(new_second).at("change"), second_change);
    t.expect_eq(f.parents(new_first).count(target), 1u);
    t.expect_eq(f.parents(new_second).count(new_first), 1u);
}

void rebase_conflict(test::Context& t) {
    VnFixture f;
    f.init();
    f.write("f.txt", "base\n");
    f.vn({"bmk", "set", "master"});
    f.commit("base");
    f.vn({"bmk", "set", "left"});
    f.vn({"new", "left"});
    f.write("f.txt", "left\n");
    f.commit("left");
    f.vn({"bmk", "set", "right"});
    f.vn({"new", "master"});
    f.write("f.txt", "right\n");
    f.commit("right");
    f.vn({"rebase", "-s", "left", "-d", "right"});
    bool conflicted = false;
    for (const LogRow& row : f.log_rows()) {
        if (row.message.find("left") != std::string::npos &&
            row.raw.find("(conflicted)") != std::string::npos)
            conflicted = true;
    }
    t.expect(conflicted);
    f.vn({"co", "left"});
    t.expect_contains(f.vn({"xs"}).out, "f.txt");
    t.expect(f.exists("f.txt.base"));
    f.vn({"resolve", "-take", "theirs", "f.txt"});
    t.expect_contains(f.vn({"xs"}).out, "no conflicts");
}

void git_bridge_import_materialize_export(test::Context& t) {
#if defined(_WIN32)
    t.expect(true);
#else
    if (!git_available()) {
        t.expect(true);
        return;
    }
    VnFixture f;
    const fs::path git_repo = make_git_repository(t, f);
    const fs::path vn_repo = f.root / "vnrepo";
    f.vn({"init", vn_repo.string(), "-git-import:" + git_repo.string()}, f.root);
    std::string log = f.vn({"log", "-no-col-titles"}, vn_repo).out;
    t.expect_contains(log, "git one");
    t.expect_contains(log, "git two");
    t.expect_eq(split_lines(f.vn({"ls", "-plain"}, vn_repo).out).size(), 1u);
    f.vn({"git", "materialize"}, vn_repo);
    t.expect_contains(f.vn({"stat"}, vn_repo).out, "working copy clean");
    t.expect_eq(f.read("a.txt", vn_repo), "one\ntwo\n");

    f.write("b.txt", "native\n", vn_repo);
    f.commit("native commit", vn_repo);
    f.vn({"git", "export"}, vn_repo);
    const fs::path git_dir = vn_repo / ".veins" / "git";
    const CommandResult subjects =
        run_shell({"git", "--git-dir", git_dir.string(), "log", "--format=%s", "--all"}, f.root);
    require_shell(t, subjects, "git log");
    t.expect_contains(subjects.out, "native commit");
    const CommandResult tree =
        run_shell({"git", "--git-dir", git_dir.string(), "show", "master:b.txt"}, f.root);
    require_shell(t, tree, "git show");
    t.expect_eq(tree.out, "native\n");
    t.expect_contains(f.vn({"fsck"}, vn_repo).out, "fsck: clean");
#endif
}

void git_bridge_invalid_import(test::Context& t) {
    (void)t;
#if defined(_WIN32)
    t.expect(true);
#else
    VnFixture f;
    const fs::path not_git = f.root / "not-git";
    fs::create_directories(not_git);
    f.failed({"init", (f.root / "bad").string(), "-git-import:" + not_git.string()},
             "not a git repository root", f.root);
#endif
}

void make_source_repository(VnFixture& f) {
    const fs::path source = f.root / "source";
    fs::create_directories(source);
    f.init(source);
    f.write("a.txt", "hello\n", source);
    f.vn({"bmk", "set", "master"}, source);
    f.commit("initial", source);
    f.vn({"access", "anonymous", "on"}, source);
}

void protocol_clone_whoami(test::Context& t) {
    VnFixture f;
    make_source_repository(f);
    const fs::path source = f.root / "source";
    const fs::path clone = f.root / "clone";
    f.vn({"clone", "file://" + source.string(), clone.string()}, f.root);
    t.expect_eq(f.read("a.txt", clone), "hello\n");
    t.expect_contains(f.vn({"log"}, clone).out, "initial");
    t.expect_contains(f.vn({"stat"}, clone).out, "working copy clean");
    t.expect_contains(f.vn({"remote", "list"}, clone).out, "origin");
    t.expect_contains(f.vn({"whoami", "origin"}, clone).out, "role: read");
}

void protocol_push_fetch(test::Context& t) {
    VnFixture f;
    make_source_repository(f);
    const fs::path source = f.root / "source";
    const std::string key_info = f.vn({"key", "generate", "integration"}, source).out;
    std::string public_key;
    for (const std::string& line : split_lines(key_info)) {
        if (line.starts_with("public key: ")) {
            public_key = line.substr(std::string("public key: ").size());
            break;
        }
    }
    t.expect(!public_key.empty());
    f.vn({"access", "add", "-role", "write", "-key", public_key, "-name", "integration"}, source);
    t.expect_contains(f.vn({"key", "show", "integration"}, source).out, "fingerprint:");
    t.expect_contains(f.vn({"key", "list"}, source).out, "integration");
    f.vn({"auth", "use", "integration"}, source);
    t.expect_contains(f.vn({"auth", "list"}, source).out, "integration");

    const fs::path clone_a = f.root / "clone-a";
    f.vn({"clone", "file://" + source.string(), clone_a.string()}, f.root);
    f.vn({"cfg", "remote.origin.key", "integration"}, clone_a);
    f.write("a.txt", "from clone a\n", clone_a);
    f.commit("clone a change", clone_a);
    const CommandResult pushed = f.vn({"push", "origin", "master"}, clone_a);
    t.expect_contains(pushed.out, "pushed master");
    t.expect_contains(f.vn({"log"}, source).out, "clone a change");
    t.expect_contains(f.vn({"whoami", "origin"}, clone_a).out, "role: write");

    const fs::path clone_b = f.root / "clone-b";
    f.vn({"clone", "file://" + source.string(), clone_b.string()}, f.root);
    f.vn({"cfg", "remote.origin.key", "integration"}, clone_b);
    f.write("b.txt", "from clone b\n", clone_b);
    f.commit("clone b change", clone_b);
    f.vn({"push", "origin", "master"}, clone_b);
    f.vn({"fetch", "origin"}, clone_a);
    t.expect_contains(f.vn({"log", "-rev", "origin/master"}, clone_a).out, "clone b change");
}

void protocol_bad_inputs(test::Context& t) {
    (void)t;
    VnFixture f;
    f.init();
    f.failed({"clone", "not-a-url", "dest"}, "unsupported URL");
    f.failed({"clone", "file:///does/not/exist", "dest"}, "error:");
}

void errors_bad_arguments(test::Context& t) {
    (void)t;
    VnFixture f;
    f.init();
    for (const std::vector<std::string>& command : std::vector<std::vector<std::string>>{
             {"go"},
             {"go", "-m", ""},
             {"rm"},
             {"ex"},
             {"show", "unknown-revision"},
             {"hash", "unknown-revision"},
             {"co", "unknown-revision"},
             {"amend", "@"},
             {"rebase", "-s", "@"},
             {"new", "-bad"},
         }) {
        f.failed(command, "error:");
    }
    f.failed({"unknown-command"}, "unknown command");
    f.failed({"help", "unknown-command"}, "unknown command");
    f.failed({"cfg", "key", "value", "extra"}, "accepts a key and one value");
}

void errors_self_test_fsck_version(test::Context& t) {
    VnFixture f;
    f.init();
    f.write("f.txt", "content\n");
    f.commit("content");
    t.expect_contains(f.vn({"self-test"}).out, "self-test: ok");
    t.expect_contains(f.vn({"fsck"}).out, "fsck: clean");
    t.expect_contains(f.vn({"fsck", "-verbose"}).out, "fsck: clean");
    t.expect_contains(f.vn({"version"}).out, "veins");
}

void errors_log_show_arguments(test::Context& t) {
    (void)t;
    VnFixture f;
    f.init();
    for (const std::vector<std::string>& command : std::vector<std::vector<std::string>>{
             {"log", "-l"}, {"log", "-f", "0"}, {"log", "-bad"}, {"show", "-bad"}}) {
        f.failed(command);
    }
}

std::vector<test::Suite> suites() {
    return {
        {"core",
         {
             {"init_version_help", core_init_version_help},
             {"outside_repository", core_outside_repository},
             {"status_list_diff_describe", core_status_list_diff_describe},
             {"commit_log_show_hash", core_commit_log_show_hash},
             {"log_limits_revisions", core_log_limits_revisions},
             {"checkout_materializes_and_new", core_checkout_materializes_and_new},
         }},
        {"worktree",
         {
             {"rename_and_delete", worktree_rename_and_delete},
             {"exclude_and_remove", worktree_exclude_and_remove},
             {"ignore_rules", worktree_ignore_rules},
             {"checkout_removes_later_files", worktree_checkout_removes_later_files},
             {"editor", worktree_editor},
         }},
        {"history",
         {
             {"log_is_topological", history_log_is_topological},
             {"amend_rewrites_descendants", history_amend_rewrites_descendants},
             {"undo_and_operation_restore", history_undo_and_operation_restore},
             {"diff_path_filter", history_diff_path_filter},
             {"show_and_diff", history_show_and_diff},
         }},
        {"refs",
         {
             {"bookmarks", refs_bookmarks},
             {"current_bookmark", refs_current_bookmark},
             {"tags", refs_tags},
             {"remote_configuration", refs_remote_configuration},
         }},
        {"config",
         {
             {"local", config_local},
             {"global_identity", config_global_identity},
             {"errors", config_errors},
             {"pager", config_pager},
         }},
        {"merge",
         {
             {"clean", merge_clean},
             {"conflict_resolve_theirs", merge_conflict_resolve_theirs},
             {"conflict_resolve_ours", merge_conflict_resolve_ours},
             {"conflict_resolve_current", merge_conflict_resolve_current},
             {"multiple", merge_multiple},
         }},
        {"rebase",
         {
             {"changes_parent", rebase_changes_parent},
             {"rewrites_descendants", rebase_rewrites_descendants},
             {"conflict", rebase_conflict},
         }},
        {"git",
         {
             {"import_materialize_export", git_bridge_import_materialize_export},
             {"invalid_import", git_bridge_invalid_import},
         }},
        {"protocol",
         {
             {"clone_whoami", protocol_clone_whoami},
             {"push_fetch", protocol_push_fetch},
             {"bad_inputs", protocol_bad_inputs},
         }},
        {"errors",
         {
             {"bad_arguments", errors_bad_arguments},
             {"self_test_fsck_version", errors_self_test_fsck_version},
             {"log_show_arguments", errors_log_show_arguments},
         }},
    };
}

} // namespace
} // namespace vn

int main(int argc, char** argv) {
    // The protocol tests run in-process, so the client may re-exec this binary as
    // a stdio server.
    if (argc >= 2 && std::string_view(argv[1]) == "serve") {
        std::vector<std::string> args;
        args.reserve(static_cast<std::size_t>(argc));
        for (int i = 0; i < argc; ++i)
            args.emplace_back(argv[i]);
        return vn::cli_run(args);
    }

    std::string suite;
    for (int i = 1; i < argc; ++i) {
        const std::string_view arg = argv[i];
        if (arg == "--suite" && i + 1 < argc) {
            suite = argv[++i];
        } else if (arg == "--list") {
            for (const vn::test::Suite& item : vn::suites())
                std::cout << item.name << "\n";
            return 0;
        } else {
            std::cerr << "unknown argument: " << arg << "\n";
            return 1;
        }
    }
    return vn::test::run_tests(vn::suites(), suite);
}
