#include "test_support.h"

#include "integration/support.h"

#include "store/store.h"

#include <filesystem>
#include <random>
#include <string>
#include <vector>

namespace vn::integration {
namespace {

void expect_no_exception(test::Context& t, const CommandResult& result,
                         std::string_view command) {
    (void)command;
    t.expect_not_contains(result.err, "exception:");
}

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);
    }
}

void errors_command_junk(test::Context& t) {
    VnFixture f;
    f.init();
    f.write("tracked.txt", "one\n");
    f.commit("initial");

    const std::string huge(200'000, 'x');
    const std::string binary("\x01\x7f\x80\xff", 4);
    const std::vector<std::string> tokens = {
        "",          "-",         "--",        "-x",          "-r",
        "-rev",      "-m",        "-message",  "-l",          "-f",
        "-a",        "-all",      "-short",    "-long",       "-plain",
        "-p",        "-v",        "-verbose",  "-gen",        "gen",
        "txt",       "bin",       "eol",       "-eol",        "@",
        "master",    "HEAD",      "0",         "1",           "999999999999999999999999",
        "a",         "a/b",       "..",        "../outside",  "/",
        "//",        ".",         ".veins",    "a.veins",     binary,
        "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "*.txt", "set", "ls", "rm",
        "mv",        "get",       "list",      "unset",       "log",
        "restore",   "revert",    "latest",    "theirs",      "ours",
        "current",   "all()",     "unknown",   huge,
    };
    const std::vector<std::string> commands = {
        "stat",   "ls",     "inf",     "log",     "show",    "hash",    "diff",
        "new",    "desc",   "go",      "amend",   "co",      "bmk",     "tag",
        "cfg",    "attr",   "op",      "undo",    "merge",   "rebase",  "xs",
        "resolve", "fsck",  "repack",  "self-test", "version", "help",   "rm",
        "mv",     "ex",     "edit",    "init",
    };

    for (const auto& command : commands) {
        for (int shape = 0; shape < 4; ++shape) {
            std::vector<std::string> args{"vn", command};
            if (shape == 1)
                args.push_back("");
            else if (shape == 2)
                args.push_back("--");
            else if (shape == 3) {
                args.push_back("-r");
                args.push_back("");
            }
            CommandResult result = f.vn(args, {}, false);
            expect_no_exception(t, result, command);
        }
    }

    std::mt19937_64 rng(0x5eed1234ull);
    std::uniform_int_distribution<std::size_t> command_pick(0, commands.size() - 1);
    std::uniform_int_distribution<std::size_t> token_pick(0, tokens.size() - 1);
    std::uniform_int_distribution<int> count_dist(0, 5);
    for (int iteration = 0; iteration < 400; ++iteration) {
        std::vector<std::string> args{"vn", commands[command_pick(rng)]};
        const int count = count_dist(rng);
        for (int i = 0; i < count; ++i)
            args.push_back(tokens[token_pick(rng)]);
        CommandResult result = f.vn(args, {}, false);
        expect_no_exception(t, result, join_args(args));
    }
}

void errors_corrupt_repository(test::Context& t) {
    VnFixture f;
    f.init();
    f.write("a.txt", "one\n");
    f.commit("first");

    std::string bad_config = "not a key value line\n";
    bad_config.push_back('\0');
    bad_config.append(std::string(100'000, 'x'));
    bad_config.push_back('\n');
    f.write(".veins/config", bad_config);

    std::string hostile_ignore(100'000, '*');
    hostile_ignore.push_back('\n');
    f.write(".vnexclude", hostile_ignore);
    f.write(".vnattribs", std::string(100'000, 'a') + "\n");

    for (const std::vector<std::string>& command :
         std::vector<std::vector<std::string>>{{"cfg", "list"},
                                               {"stat"},
                                               {"log"},
                                               {"inf"},
                                               {"fsck"},
                                               {"version"}}) {
        CommandResult result = f.vn(command, {}, false);
        expect_no_exception(t, result, join_args(command));
    }

    const fs::path heads = f.repo / ".veins" / "op-heads";
    if (write_file(heads / "not-a-head", bytes_of("junk")))
        (void)write_file(heads / std::string(64, 'z'), bytes_of("junk"));
    for (const std::vector<std::string>& command :
         std::vector<std::vector<std::string>>{{"stat"}, {"log"}, {"fsck"}}) {
        CommandResult result = f.vn(command, {}, false);
        expect_no_exception(t, result, join_args(command));
    }

    const fs::path packs = f.repo / ".veins" / "store" / "packs";
    std::error_code ec;
    if (fs::is_directory(packs, ec)) {
        for (const auto& entry : fs::directory_iterator(packs, ec)) {
            if (ec)
                break;
            if (entry.path().extension() != ".vpack")
                continue;
            auto data = read_file_opt(entry.path());
            if (!data || data->empty())
                continue;
            (*data)[data->size() / 2] ^= 0xff;
            (void)write_file(entry.path(), bytes_of(*data));
            break;
        }
    }

    for (const std::vector<std::string>& command :
         std::vector<std::vector<std::string>>{
             {"stat"}, {"log"}, {"fsck"}, {"show"}, {"ls"}, {"hash"}, {"inf"},
             {"self-test"}, {"repack"}}) {
        CommandResult result = f.vn(command, {}, false);
        expect_no_exception(t, result, join_args(command));
    }
}

} // namespace

test::Suite errors_suite() {
    return {"errors",
            {
                {"bad_arguments", errors_bad_arguments},
                {"self_test_fsck_version", errors_self_test_fsck_version},
                {"log_show_arguments", errors_log_show_arguments},
                {"command_junk", errors_command_junk},
                {"corrupt_repository", errors_corrupt_repository},
            }};
}
} // namespace vn::integration

