#include "net_commands.h"

#include "auth.h"
#include "crypto.h"
#include "promisor.h"
#include "protocol.h"
#include "server.h"
#include "store.h"
#include "worktree.h"

#include <algorithm>
#include <charconv>
#include <cstddef>
#include <cstring>
#include <iostream>
#include <optional>
#include <set>
#include <string>
#include <vector>

namespace vn {

namespace {

bool starts_with(std::string_view text, std::string_view prefix) {
    return text.size() >= prefix.size() && text.substr(0, prefix.size()) == prefix;
}

bool is_flag(std::string_view arg) {
    return !arg.empty() && arg.front() == '-';
}

std::string arg_at(const std::vector<std::string>& args, std::size_t index) {
    return index < args.size() ? args[index] : std::string();
}

void report_connect_failure(std::string_view fallback) {
    error_prefix();
    const std::string& detail = proto::Client::last_connect_error();
    std::cout << (detail.empty() ? std::string(fallback) : detail) << "\n";
}

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

std::string remote_key(std::string_view remote, std::string_view field) {
    std::string out = "remote.";
    out += remote;
    out.push_back('.');
    out += field;
    return out;
}

std::string last_segment(std::string_view path) {
    while (path.size() > 1 && path.back() == '/')
        path.remove_suffix(1);
    const auto slash = path.rfind('/');
    if (slash != std::string_view::npos && slash + 1 < path.size())
        return std::string(path.substr(slash + 1));
    if (!path.empty() && path != "/")
        return std::string(path);
    return "repo";
}

bool same_id(const Id& a, const Id& b) {
    return std::memcmp(a.data(), b.data(), ID_LEN) == 0;
}

void report_client_error(const proto::Client& client, std::string_view context) {
    error_prefix();
    if (!client.error().empty())
        std::cout << context << ": " << client.error() << "\n";
    else
        std::cout << context << "\n";
}

std::optional<Id> default_target(const std::vector<proto::RefInfo>& refs) {
    for (const auto& ref : refs) {
        if (ref.kind == 0 && (ref.name == "main" || ref.name == "master"))
            return ref.target;
    }
    for (const auto& ref : refs) {
        if (ref.kind == 0)
            return ref.target;
    }
    return std::nullopt;
}

std::optional<std::string> default_ref_name(const std::vector<proto::RefInfo>& refs) {
    for (const auto& ref : refs) {
        if (ref.kind == 0 && (ref.name == "main" || ref.name == "master"))
            return ref.name;
    }
    for (const auto& ref : refs) {
        if (ref.kind == 0)
            return ref.name;
    }
    return std::nullopt;
}

std::vector<Id> selected_commits(const std::vector<proto::RefInfo>& refs, std::string_view policy) {
    std::vector<Id> out;
    if (policy == "none")
        return out;
    if (policy == "head") {
        if (auto target = default_target(refs))
            out.push_back(*target);
        return out;
    }
    for (const auto& ref : refs)
        out.push_back(ref.target);
    return out;
}

bool set_bookmark(View& view, std::string_view name, const Id& target) {
    if (auto index = find_bookmark(view, name)) {
        view.bookmarks[*index].targets.adds = {target};
        view.bookmarks[*index].targets.removes.clear();
        return true;
    }
    Bookmark bookmark;
    bookmark.name = std::string(name);
    bookmark.targets.adds = {target};
    view.bookmarks.push_back(std::move(bookmark));
    return true;
}

bool set_tag(View& view, std::string_view name, const Id& target) {
    if (auto index = find_tag(view, name)) {
        view.tags[*index].target = target;
        return true;
    }
    view.tags.push_back(TagRef{std::string(name), target});
    return true;
}

bool set_remote_ref(View& view, std::string_view remote, std::string_view name, const Id& target) {
    for (auto& ref : view.remote_refs) {
        if (ref.remote == remote && ref.name == name) {
            ref.target = target;
            return true;
        }
    }
    view.remote_refs.push_back(RemoteRef{std::string(remote), std::string(name), target});
    return true;
}

bool apply_refs(const fs::path& root, const std::vector<proto::RefInfo>& refs,
                std::string_view remote, bool clone) {
    Store store = Store::open_all(root);
    auto tx = Txn::begin(root, store);
    if (!tx)
        return false;
    for (const auto& ref : refs) {
        if (ref.kind == 1) {
            set_tag(tx->view(), ref.name, ref.target);
        } else if (clone) {
            set_bookmark(tx->view(), ref.name, ref.target);
        } else {
            set_remote_ref(tx->view(), remote, ref.name, ref.target);
            if (!find_bookmark(tx->view(), ref.name))
                set_bookmark(tx->view(), ref.name, ref.target);
        }
    }
    rebuild_heads(tx->view());
    if (clone) {
        if (auto target = default_target(refs)) {
            auto child = create_working_copy_commit(*tx, *target);
            if (!child)
                return false;
            set_workspace(tx->view(), *child);
            rebuild_heads(tx->view());
        }
    }
    const bool ok = tx->finish("clone").has_value();
    if (ok && clone) {
        if (auto name = default_ref_name(refs))
            (void)set_current_bookmark(root, *name);
        else
            (void)clear_current_bookmark(root);
    }
    return ok;
}

struct Walker {
    Walker(Store& store, bool want_objects) : store(store), want_objects(want_objects) {}

    Store& store;
    bool want_objects = false;
    std::set<Id> blobs;
    std::set<Id> conflicts;
    std::set<Id> chunks;
    std::set<Id> objects;
    std::vector<Id> chunk_out;
    std::vector<Id> object_out;

    void add_object(const Id& id) {
        if (want_objects && objects.insert(id).second)
            object_out.push_back(id);
    }

    void walk_blob(const Id& id) {
        if (!blobs.insert(id).second)
            return;
        add_object(id);
        auto body = store.read_body(id, TYPE_BLOB);
        if (!body)
            return;
        auto blob = decode_blob(bytes_of(*body));
        if (!blob)
            return;
        if (blob->form == BlobForm::Leaf) {
            for (const auto& entry : blob->entries) {
                if (chunks.insert(entry.id).second)
                    chunk_out.push_back(entry.id);
                add_object(entry.id);
            }
        } else if (blob->form == BlobForm::Interior) {
            for (const auto& entry : blob->entries)
                walk_blob(entry.id);
        }
    }

    void walk_conflict(const Id& id) {
        if (!conflicts.insert(id).second)
            return;
        add_object(id);
        auto body = store.read_body(id, TYPE_CONFLICT);
        if (!body)
            return;
        auto conflict = decode_conflict(bytes_of(*body));
        if (!conflict)
            return;
        for (const auto& value : conflict->adds) {
            if (value.target)
                walk_value(value.kind, *value.target);
        }
        for (const auto& value : conflict->removes) {
            if (value.target)
                walk_value(value.kind, *value.target);
        }
    }

    void walk_value(std::uint8_t kind, const Id& id) {
        if (kind == KIND_SUBTREE)
            walk_tree(id);
        else if (kind == KIND_CONFLICT)
            walk_conflict(id);
        else
            walk_blob(id);
    }

    void walk_tree(const Id& id) {
        add_object(id);
        auto body = store.read_body(id, TYPE_TREE);
        if (!body)
            return;
        auto tree = decode_tree(bytes_of(*body));
        if (!tree)
            return;
        for (const auto& entry : tree->entries) {
            if (entry.kind == KIND_SUBTREE)
                walk_tree(entry.target);
            else if (entry.kind == KIND_CONFLICT)
                walk_conflict(entry.target);
            else if (entry.kind != KIND_SUBMODULE)
                walk_blob(entry.target);
        }
    }
};

std::vector<Id> chunks_for_commits(Store& store, const std::vector<Id>& commits) {
    Walker walker{store, false};
    for (const auto& id : commits) {
        auto loaded = load_commit(store, id);
        if (loaded)
            walker.walk_tree(loaded->commit.root_tree);
    }
    return std::move(walker.chunk_out);
}

std::vector<Id> objects_for_commits(Store& store, const std::vector<Id>& commits) {
    Walker walker{store, true};
    for (const auto& id : commits) {
        walker.add_object(id);
        auto loaded = load_commit(store, id);
        if (loaded)
            walker.walk_tree(loaded->commit.root_tree);
    }
    return std::move(walker.object_out);
}

bool send_chunks(proto::Client& client, const fs::path& root, const std::vector<Id>& chunks) {
    constexpr std::size_t BATCH = 4096;
    for (std::size_t offset = 0; offset < chunks.size(); offset += BATCH) {
        const std::size_t end = std::min(offset + BATCH, chunks.size());
        std::vector<Id> batch(chunks.begin() + static_cast<std::ptrdiff_t>(offset),
                              chunks.begin() + static_cast<std::ptrdiff_t>(end));
        if (!client.get_chunks(root, batch))
            return false;
    }
    return true;
}

bool send_missing_chunks(proto::Client& client, const fs::path& root,
                         const std::vector<Id>& chunks) {
    Store store = Store::open_all(root);
    std::vector<Id> missing;
    for (const auto& id : chunks) {
        if (!store.find(id))
            missing.push_back(id);
    }
    return send_chunks(client, root, missing);
}

std::optional<std::string> config_value(const fs::path& root, std::string_view key) {
    return repo_config_value(root, key);
}

std::vector<std::string> list_remote_names(const fs::path& root) {
    std::vector<std::string> out;
    auto data = read_file_opt(config_path(root));
    if (!data)
        return out;
    const std::string_view text(reinterpret_cast<const char*>(data->data()), data->size());
    std::size_t start = 0;
    for (std::size_t i = 0; i <= text.size(); ++i) {
        if (i != text.size() && text[i] != '\n')
            continue;
        const std::string_view line = text.substr(start, i - start);
        if (starts_with(line, "remote.")) {
            const auto dot = line.find(".url", 7);
            if (dot != std::string_view::npos && dot > 7)
                out.emplace_back(line.substr(7, dot - 7));
        }
        start = i + 1;
    }
    return out;
}

std::string role_text(std::uint8_t role) {
    if (role == 2)
        return "write";
    if (role == 1)
        return "read";
    return "anonymous";
}

void print_key(const auth::Key& key) {
    std::cout << "name: " << key.name << "\n";
    std::cout << "public key: " << format_public_key(key.public_key) << "\n";
    std::cout << "fingerprint: " << key.fingerprint << "\n";
}

void auth_usage() {
    std::cout << "usage: vn auth <use|list|remove> ...\n";
    std::cout << "  vn auth use <key> [<host|url>]   set the default or host key\n";
    std::cout << "  vn auth list                     show stored key mappings\n";
    std::cout << "  vn auth remove [<host|url>]      remove a mapping (default if "
                 "omitted)\n";
}

std::optional<PublicKey> read_public_key(std::string_view arg) {
    if (starts_with(arg, "ed25519:"))
        return parse_public_key(arg);
    auto data = read_file_opt(path_from_bytes(arg));
    if (!data)
        return std::nullopt;
    const std::string text =
        trim_text(std::string_view(reinterpret_cast<const char*>(data->data()), data->size()));
    return parse_public_key(text);
}

} // namespace

// ---------------------------------------------------------------------------
// remote
// ---------------------------------------------------------------------------

int remote_run(const std::vector<std::string>& args) {
    const std::string sub = arg_at(args, 2);
    if (sub.empty()) {
        error_prefix();
        std::cout << "expected a remote subcommand (add, set-url, list, remove)\n";
        return 1;
    }
    auto repo = discover_repo(".");
    if (!repo) {
        error_prefix();
        std::cout << "not a veins repository\n";
        return 1;
    }
    const fs::path root = *repo;

    if (sub == "add" || sub == "set-url") {
        const bool replace = sub == "set-url";
        std::string name;
        std::string url;
        std::optional<std::string> key;
        std::optional<std::string> pin;
        for (std::size_t i = 3; i < args.size(); ++i) {
            const std::string& arg = args[i];
            if (starts_with(arg, "-key:")) {
                key = arg.substr(5);
            } else if (starts_with(arg, "-pin:")) {
                pin = arg.substr(5);
            } else if (is_flag(arg)) {
                error_prefix();
                std::cout << "unknown flag: " << arg << "\n";
                return 1;
            } else if (name.empty()) {
                name = arg;
            } else if (url.empty()) {
                url = arg;
            } else {
                error_prefix();
                std::cout << "too many arguments\n";
                return 1;
            }
        }
        if (name.empty() || url.empty()) {
            error_prefix();
            std::cout << (replace ? "remote set-url requires a name and URL\n"
                                  : "remote add requires a name and URL\n");
            return 1;
        }
        const std::string url_key = remote_key(name, "url");
        const auto existing = config_value(root, url_key);
        if (existing && !replace) {
            error_prefix();
            std::cout << "remote already exists: " << name << "\n";
            return 1;
        }
        if (!existing && replace) {
            error_prefix();
            std::cout << "unknown remote: " << name << "\n";
            return 1;
        }
        if (!repo_config_set(root, url_key, url)) {
            error_prefix();
            std::cout << "cannot write repository config\n";
            return 1;
        }
        if (key) {
            const std::string field = remote_key(name, "key");
            const bool ok =
                key->empty() ? repo_config_remove(root, field) : repo_config_set(root, field, *key);
            if (!ok) {
                error_prefix();
                std::cout << "cannot write repository config\n";
                return 1;
            }
        }
        if (pin) {
            const std::string field = remote_key(name, "tls-pin");
            const bool ok =
                pin->empty() ? repo_config_remove(root, field) : repo_config_set(root, field, *pin);
            if (!ok) {
                error_prefix();
                std::cout << "cannot write repository config\n";
                return 1;
            }
        }
        return 0;
    }

    if (sub == "list" || sub == "ls") {
        for (const auto& name : list_remote_names(root)) {
            const auto url = config_value(root, remote_key(name, "url"));
            std::cout << name << "\t" << (url ? *url : std::string()) << "\n";
        }
        return 0;
    }

    if (sub == "remove" || sub == "rm") {
        const std::string name = arg_at(args, 3);
        if (name.empty()) {
            error_prefix();
            std::cout << "remote remove requires a name\n";
            return 1;
        }
        if (!config_value(root, remote_key(name, "url"))) {
            error_prefix();
            std::cout << "unknown remote: " << name << "\n";
            return 1;
        }
        (void)repo_config_remove(root, remote_key(name, "url"));
        (void)repo_config_remove(root, remote_key(name, "key"));
        (void)repo_config_remove(root, remote_key(name, "tls-pin"));
        return 0;
    }

    error_prefix();
    std::cout << "unknown remote subcommand: " << sub << "\n";
    return 1;
}

// ---------------------------------------------------------------------------
// clone
// ---------------------------------------------------------------------------

int clone_run(const std::vector<std::string>& args) {
    std::string url;
    std::string path;
    std::string policy = "head";
    std::string key_name;
    bool key_explicit = false;
    std::string tls_pin;
    for (std::size_t i = 2; i < args.size(); ++i) {
        const std::string& arg = args[i];
        if (starts_with(arg, "-blobs:")) {
            policy = arg.substr(7);
        } else if (starts_with(arg, "-key:")) {
            key_name = arg.substr(5);
            if (starts_with(key_name, "ed25519:")) {
                error_prefix();
                std::cout << "-key: expects a local key name, not a public key\n";
                return 1;
            }
            key_explicit = true;
        } else if (starts_with(arg, "-pin:")) {
            tls_pin = arg.substr(5);
        } else if (is_flag(arg)) {
            error_prefix();
            std::cout << "unknown flag: " << arg << "\n";
            return 1;
        } else if (url.empty()) {
            url = arg;
        } else {
            path = arg;
        }
    }
    if (url.empty()) {
        error_prefix();
        std::cout << "clone requires a URL\n";
        return 1;
    }
    const auto parsed = proto::parse_url(url);
    if (!parsed) {
        error_prefix();
        std::cout << "unsupported URL\n";
        return 1;
    }
    if (path.empty())
        path = last_segment(parsed->path);
    auto repo = init_repo(path_from_bytes(path));
    if (!repo) {
        error_prefix();
        std::cout << "cannot create repository\n";
        return 1;
    }
    const fs::path root = *repo;

    if (key_name.empty()) {
        if (auto fallback = auth::key_for_url(url))
            key_name = *fallback;
    }
    (void)repo_config_set(root, remote_key("origin", "url"), url);
    if (key_explicit && !key_name.empty())
        (void)repo_config_set(root, remote_key("origin", "key"), key_name);
    if (!tls_pin.empty())
        (void)repo_config_set(root, remote_key("origin", "tls-pin"), tls_pin);

    const std::string repo_name = proto::url_repo_name(url);
    auto client = proto::Client::connect(url, key_name, repo_name, tls_pin);
    if (!client) {
        report_connect_failure("cannot connect or authenticate");
        return 1;
    }
    std::vector<proto::RefInfo> refs;
    if (!client->list_refs(refs)) {
        report_client_error(*client, "cannot list remote refs");
        return 1;
    }
    std::vector<Id> wants;
    for (const auto& ref : refs)
        wants.push_back(ref.target);
    if (wants.empty()) {
        info_prefix();
        std::cout << "cloned empty repository into " << path << "\n";
        return 0;
    }
    if (!client->negotiate(wants, {})) {
        report_client_error(*client, "negotiation failed");
        return 1;
    }
    if (!client->fetch_skeleton(root, wants)) {
        report_client_error(*client, "fetch failed");
        return 1;
    }
    {
        Store store = Store::open_all(root);
        const auto commits = selected_commits(refs, policy);
        const auto chunks = chunks_for_commits(store, commits);
        if (!send_chunks(*client, root, chunks)) {
            report_client_error(*client, "chunk fetch failed");
            return 1;
        }
    }
    if (!apply_refs(root, refs, "origin", true)) {
        error_prefix();
        std::cout << "cannot write repository state\n";
        return 1;
    }
    (void)repo_config_set(root, "promisor", "origin");
    install_promisor_fetcher();
    if (policy == "none") {
        info_prefix();
        std::cout << "cloned metadata only; blobs are promised\n";
    }

    int checkout_status = 1;
    {
        Store store = Store::open_all(root);
        auto view = current_view(root, store);
        if (view) {
            if (auto wc = working_copy_id(*view)) {
                auto body = store.read_body(*wc, TYPE_COMMIT);
                if (body) {
                    auto commit = decode_commit(bytes_of(*body));
                    if (commit) {
                        checkout_status = checkout_materialize_commit(root, store, std::nullopt,
                                                                      commit->root_tree);
                    }
                }
            }
        }
    }
    if (checkout_status != 0) {
        info_prefix();
        std::cout << "cloned; checkout reported " << checkout_status << "\n";
    }
    info_prefix();
    std::cout << "cloned into " << path << "\n";
    return 0;
}

// ---------------------------------------------------------------------------
// fetch
// ---------------------------------------------------------------------------

int fetch_run(const std::vector<std::string>& args) {
    std::string remote_name = "origin";
    std::string path = ".";
    std::string explicit_key;
    std::string explicit_pin;
    bool have_remote = false;
    for (std::size_t i = 2; i < args.size(); ++i) {
        const std::string& arg = args[i];
        if (starts_with(arg, "-key:")) {
            explicit_key = arg.substr(5);
            if (starts_with(explicit_key, "ed25519:")) {
                error_prefix();
                std::cout << "-key: expects a local key name, not a public key\n";
                return 1;
            }
        } else if (starts_with(arg, "-pin:")) {
            explicit_pin = arg.substr(5);
        } else if (is_flag(arg)) {
            error_prefix();
            std::cout << "unknown flag: " << arg << "\n";
            return 1;
        } else if (!have_remote) {
            remote_name = arg;
            have_remote = true;
        } else {
            path = arg;
        }
    }
    auto repo = discover_repo(path_from_bytes(path));
    if (!repo) {
        error_prefix();
        std::cout << "not a veins repository\n";
        return 1;
    }
    const fs::path root = *repo;
    auto url = config_value(root, remote_key(remote_name, "url"));
    if (!url) {
        error_prefix();
        std::cout << "unknown remote\n";
        return 1;
    }
    std::string key;
    if (!explicit_key.empty()) {
        key = explicit_key;
    } else {
        auto configured = config_value(root, remote_key(remote_name, "key"));
        if (configured && auth::local_key_exists(*configured))
            key = *configured;
        if (key.empty()) {
            if (auto fallback = auth::key_for_url(*url))
                key = *fallback;
        }
    }
    std::string pin;
    if (!explicit_pin.empty()) {
        pin = explicit_pin;
    } else if (auto configured = config_value(root, remote_key(remote_name, "tls-pin"))) {
        pin = *configured;
    }
    const std::string repo_name = proto::url_repo_name(*url);
    auto client = proto::Client::connect(*url, key, repo_name, pin);
    if (!client) {
        report_connect_failure("cannot connect or authenticate");
        return 1;
    }
    std::vector<proto::RefInfo> refs;
    if (!client->list_refs(refs)) {
        report_client_error(*client, "cannot list remote refs");
        return 1;
    }
    std::vector<Id> haves = read_heads(root);
    std::vector<Id> wants;
    for (const auto& ref : refs)
        wants.push_back(ref.target);
    if (wants.empty()) {
        info_prefix();
        std::cout << "no refs to fetch\n";
        return 0;
    }
    if (!client->negotiate(wants, haves)) {
        report_client_error(*client, "negotiation failed");
        return 1;
    }
    if (!client->fetch_skeleton(root, wants)) {
        report_client_error(*client, "fetch failed");
        return 1;
    }
    {
        Store store = Store::open_all(root);
        const auto chunks = chunks_for_commits(store, wants);
        if (!send_missing_chunks(*client, root, chunks)) {
            report_client_error(*client, "chunk fetch failed");
            return 1;
        }
    }
    if (!apply_refs(root, refs, remote_name, false)) {
        error_prefix();
        std::cout << "cannot write repository state\n";
        return 1;
    }
    info_prefix();
    std::cout << "fetched from " << remote_name << "\n";
    return 0;
}

// ---------------------------------------------------------------------------
// push
// ---------------------------------------------------------------------------

int push_run(const std::vector<std::string>& args) {
    std::string remote_name = "origin";
    std::string bookmark;
    std::string explicit_key;
    std::string explicit_pin;
    std::string path = ".";
    bool have_remote = false;
    for (std::size_t i = 2; i < args.size(); ++i) {
        const std::string& arg = args[i];
        if (starts_with(arg, "-key:")) {
            explicit_key = arg.substr(5);
            if (starts_with(explicit_key, "ed25519:")) {
                error_prefix();
                std::cout << "-key: expects a local key name, not a public key\n";
                return 1;
            }
        } else if (starts_with(arg, "-pin:")) {
            explicit_pin = arg.substr(5);
        } else if (is_flag(arg)) {
            error_prefix();
            std::cout << "unknown flag: " << arg << "\n";
            return 1;
        } else if (!have_remote) {
            remote_name = arg;
            have_remote = true;
        } else if (bookmark.empty()) {
            bookmark = arg;
        } else {
            path = arg;
        }
    }
    auto repo = discover_repo(path_from_bytes(path));
    if (!repo) {
        error_prefix();
        std::cout << "not a veins repository\n";
        return 1;
    }
    const fs::path root = *repo;
    if (bookmark.empty()) {
        if (auto current = current_bookmark_name(root))
            bookmark = *current;
    }
    if (bookmark.empty()) {
        error_prefix();
        std::cout << "push requires a bookmark name (or a current bookmark)\n";
        return 1;
    }
    auto url = config_value(root, remote_key(remote_name, "url"));
    if (!url) {
        error_prefix();
        std::cout << "unknown remote\n";
        return 1;
    }
    std::string key;
    if (!explicit_key.empty()) {
        key = explicit_key;
    } else {
        auto configured = config_value(root, remote_key(remote_name, "key"));
        if (configured && auth::local_key_exists(*configured))
            key = *configured;
        if (key.empty()) {
            if (auto fallback = auth::key_for_url(*url))
                key = *fallback;
        }
    }
    std::string pin;
    if (!explicit_pin.empty()) {
        pin = explicit_pin;
    } else if (auto configured = config_value(root, remote_key(remote_name, "tls-pin"))) {
        pin = *configured;
    }

    std::optional<Id> target;
    std::vector<Id> commits;
    std::vector<Id> objects;
    {
        Store store = Store::open_all(root);
        auto view = current_view(root, store);
        View empty;
        const View& current = view ? *view : empty;
        target = resolve_revision(store, current, bookmark);
        if (!target) {
            error_prefix();
            std::cout << "unknown bookmark: " << bookmark << "\n";
            return 1;
        }
        const std::array<Id, 1> roots{*target};
        commits = collect_commits(store, roots);
        objects = objects_for_commits(store, commits);
    }
    const std::string repo_name = proto::url_repo_name(*url);
    auto client = proto::Client::connect(*url, key, repo_name, pin);
    if (!client) {
        report_connect_failure("cannot connect or authenticate");
        return 1;
    }
    std::vector<proto::RefInfo> refs;
    if (!client->list_refs(refs)) {
        report_client_error(*client, "cannot list remote refs");
        return 1;
    }
    std::optional<Id> old;
    for (const auto& ref : refs) {
        if (ref.name == bookmark)
            old = ref.target;
    }
    if (old && same_id(*old, *target)) {
        info_prefix();
        std::cout << "nothing to push, everything is up to date\n";
        return 0;
    }
    if (!client->push_objects(root, objects)) {
        report_client_error(*client, "push failed");
        return 1;
    }
    std::vector<proto::UpdateRef> updates;
    updates.push_back(proto::UpdateRef{bookmark, old, target});
    if (!client->update_refs(updates)) {
        report_client_error(*client, "ref update rejected");
        return 1;
    }
    info_prefix();
    std::cout << "pushed " << bookmark << " to " << remote_name << "\n";
    return 0;
}

// ---------------------------------------------------------------------------
// serve
// ---------------------------------------------------------------------------

int serve_run(const std::vector<std::string>& args) {
    bool stdio_mode = false;
    std::string listen;
    std::string root = ".";
    std::string cert;
    std::string key;
    std::string repo_path = ".";
    std::uint64_t quota_bytes = 0;
    for (std::size_t i = 2; i < args.size(); ++i) {
        const std::string& arg = args[i];
        if (arg == "-stdio") {
            stdio_mode = true;
            if (i + 1 < args.size())
                repo_path = args[++i];
        } else if (arg == "-listen") {
            if (i + 1 < args.size())
                listen = args[++i];
        } else if (arg == "-root") {
            if (i + 1 < args.size())
                root = args[++i];
        } else if (arg == "-tls-cert") {
            if (i + 1 < args.size())
                cert = args[++i];
        } else if (arg == "-tls-key") {
            if (i + 1 < args.size())
                key = args[++i];
        } else if (arg == "-quota") {
            if (i + 1 >= args.size()) {
                error_prefix();
                std::cout << "-quota requires a byte count\n";
                return 1;
            }
            const std::string& value = args[++i];
            std::uint64_t parsed = 0;
            const auto result = std::from_chars(value.data(), value.data() + value.size(), parsed);
            if (result.ec != std::errc() || result.ptr != value.data() + value.size()) {
                error_prefix();
                std::cout << "-quota requires a byte count\n";
                return 1;
            }
            quota_bytes = parsed;
        } else {
            error_prefix();
            std::cout << "unknown serve option: " << arg << "\n";
            return 1;
        }
    }
    if (stdio_mode) {
        auto repo = discover_repo(path_from_bytes(repo_path));
        if (!repo) {
            error_prefix();
            std::cout << "not a veins repository\n";
            return 1;
        }
        return server::serve_stdio(*repo, quota_bytes);
    }
    if (listen.empty()) {
        error_prefix();
        std::cout << "serve requires -stdio or -listen\n";
        return 1;
    }
    if (cert.empty() || key.empty()) {
        error_prefix();
        std::cout << "TLS requires -tls-cert and -tls-key\n";
        return 1;
    }
    return server::serve_listen(listen, path_from_bytes(root), cert, key, quota_bytes);
}

// ---------------------------------------------------------------------------
// key
// ---------------------------------------------------------------------------

int key_run(const std::vector<std::string>& args) {
    const std::string sub = arg_at(args, 2);
    if (sub.empty()) {
        error_prefix();
        std::cout << "expected key subcommand (generate, list, show, import)\n";
        return 1;
    }
    if (sub == "generate") {
        const std::string name = arg_at(args, 3);
        if (name.empty()) {
            error_prefix();
            std::cout << "key generate requires a name\n";
            return 1;
        }
        auto key = auth::generate_key(name);
        if (!key) {
            error_prefix();
            std::cout << "cannot create key\n";
            return 1;
        }
        print_key(*key);
        return 0;
    }
    if (sub == "list") {
        for (const auto& name : auth::list_key_names()) {
            if (auto key = auth::load_key(name))
                print_key(*key);
        }
        return 0;
    }
    if (sub == "show") {
        const std::string name = arg_at(args, 3);
        if (name.empty()) {
            error_prefix();
            std::cout << "key show requires a name\n";
            return 1;
        }
        auto key = auth::load_key(name);
        if (!key) {
            error_prefix();
            std::cout << "key not found or has unsafe permissions\n";
            return 1;
        }
        print_key(*key);
        return 0;
    }
    if (sub == "import") {
        error_prefix();
        std::cout << "OpenSSH key import is not supported\n";
        return 1;
    }
    error_prefix();
    std::cout << "unknown key subcommand: " << sub << "\n";
    return 1;
}

// ---------------------------------------------------------------------------
// auth
// ---------------------------------------------------------------------------

int auth_run(const std::vector<std::string>& args) {
    const std::string sub = arg_at(args, 2);
    if (sub.empty()) {
        auth_usage();
        return 1;
    }
    if (sub == "use") {
        const std::string name = arg_at(args, 3);
        if (name.empty()) {
            auth_usage();
            return 1;
        }
        if (!auth::load_key(name)) {
            error_prefix();
            std::cout << "key not found or has unsafe permissions: " << name << "\n";
            return 1;
        }
        const std::string target = auth::normalize_target(arg_at(args, 4));
        if (!auth::set_key(target, name)) {
            error_prefix();
            std::cout << "cannot write auth configuration\n";
            return 1;
        }
        if (target == "default")
            std::cout << "default key set to " << name << "\n";
        else
            std::cout << "key for " << target << " set to " << name << "\n";
        return 0;
    }
    if (sub == "list") {
        const auto lines = auth::list_credential_lines();
        if (lines.empty())
            std::cout << "no stored credentials\n";
        for (const auto& line : lines)
            std::cout << line;
        return 0;
    }
    if (sub == "remove") {
        const std::string target = auth::normalize_target(arg_at(args, 3));
        if (auth::remove_key(target)) {
            std::cout << "removed " << target << "\n";
            return 0;
        }
        error_prefix();
        std::cout << "no credential for " << target << "\n";
        return 1;
    }
    error_prefix();
    std::cout << "unknown auth subcommand: " << sub << "\n";
    auth_usage();
    return 1;
}

// ---------------------------------------------------------------------------
// access
// ---------------------------------------------------------------------------

int access_run(const std::vector<std::string>& args) {
    const std::string sub = arg_at(args, 2);
    if (sub.empty()) {
        error_prefix();
        std::cout << "expected access subcommand\n";
        return 1;
    }
    auto repo = discover_repo(".");
    if (!repo) {
        error_prefix();
        std::cout << "not a veins repository\n";
        return 1;
    }
    const fs::path root = *repo;
    if (sub == "add") {
        std::string role;
        std::string key_arg;
        std::string name;
        for (std::size_t i = 3; i < args.size(); ++i) {
            const std::string& arg = args[i];
            if (arg == "-role" && i + 1 < args.size()) {
                role = args[++i];
            } else if (arg == "-key" && i + 1 < args.size()) {
                key_arg = args[++i];
            } else if (arg == "-name" && i + 1 < args.size()) {
                name = args[++i];
            } else {
                error_prefix();
                std::cout << "unknown access add option: " << arg << "\n";
                return 1;
            }
        }
        if (role.empty() || key_arg.empty()) {
            error_prefix();
            std::cout << "access add requires -role and -key\n";
            return 1;
        }
        std::uint8_t role_code = auth::ROLE_READ;
        if (role == "write") {
            role_code = auth::ROLE_WRITE;
        } else if (role != "read") {
            error_prefix();
            std::cout << "role must be read or write\n";
            return 1;
        }
        auto public_key = read_public_key(key_arg);
        if (!public_key) {
            error_prefix();
            std::cout << "invalid public key\n";
            return 1;
        }
        if (!auth::add_access(root, role_code, *public_key, name)) {
            error_prefix();
            std::cout << "cannot add key\n";
            return 1;
        }
        info_prefix();
        std::cout << "access granted\n";
        return 0;
    }
    if (sub == "list") {
        const auth::Access access = auth::load_access(root);
        if (!access.valid) {
            error_prefix();
            std::cout << "invalid access file at line " << access.error_line << "\n";
            return 1;
        }
        std::cout << "anonymous: " << (access.anonymous_read ? "read" : "off") << "\n";
        for (const auto& entry : access.entries) {
            std::cout << (entry.role == auth::ROLE_WRITE ? "write" : "read") << " "
                      << key_fingerprint(entry.public_key) << " " << entry.name << "\n";
        }
        return 0;
    }
    if (sub == "remove") {
        const std::string arg = arg_at(args, 3);
        if (arg.empty()) {
            error_prefix();
            std::cout << "access remove requires a fingerprint or name\n";
            return 1;
        }
        const bool is_fingerprint = arg.size() == 26;
        const std::string fingerprint = is_fingerprint ? arg : std::string();
        const std::string name = is_fingerprint ? std::string() : arg;
        if (!auth::remove_access(root, fingerprint, name)) {
            error_prefix();
            std::cout << "key not found or cannot write access file\n";
            return 1;
        }
        info_prefix();
        std::cout << "access removed\n";
        return 0;
    }
    if (sub == "anonymous") {
        const bool on = arg_at(args, 3) == "on";
        if (!auth::set_anonymous(root, on)) {
            error_prefix();
            std::cout << "cannot update access file\n";
            return 1;
        }
        return 0;
    }
    error_prefix();
    std::cout << "unknown access subcommand: " << sub << "\n";
    return 1;
}

// ---------------------------------------------------------------------------
// whoami
// ---------------------------------------------------------------------------

int whoami_run(const std::vector<std::string>& args) {
    std::string remote = "origin";
    std::string url;
    std::string key;
    std::string repo_name;
    std::string pin;
    const std::string arg = arg_at(args, 2);
    if (!arg.empty()) {
        if (starts_with(arg, "file://") || starts_with(arg, "ssh://") ||
            starts_with(arg, "veins://")) {
            url = arg;
            repo_name = proto::url_repo_name(url);
        } else {
            remote = arg;
        }
    }
    if (url.empty()) {
        auto repo = discover_repo(".");
        if (!repo) {
            error_prefix();
            std::cout << "not a veins repository\n";
            return 1;
        }
        const fs::path root = *repo;
        auto configured = config_value(root, remote_key(remote, "url"));
        if (!configured) {
            error_prefix();
            std::cout << "unknown remote\n";
            return 1;
        }
        url = *configured;
        if (auto k = config_value(root, remote_key(remote, "key"))) {
            if (auth::local_key_exists(*k))
                key = *k;
        }
        if (auto p = config_value(root, remote_key(remote, "tls-pin")))
            pin = *p;
        repo_name = proto::url_repo_name(url);
    }
    if (key.empty()) {
        if (auto fallback = auth::key_for_url(url))
            key = *fallback;
    }
    auto client = proto::Client::connect(url, key, repo_name, pin);
    if (!client) {
        report_connect_failure("cannot authenticate");
        return 1;
    }
    std::uint8_t role = 0;
    std::string fingerprint;
    if (!client->whoami(role, fingerprint)) {
        error_prefix();
        std::cout << "cannot authenticate\n";
        return 1;
    }
    std::cout << "role: " << role_text(role) << "\n";
    std::cout << "fingerprint: " << base32_text(bytes_of(fingerprint)) << "\n";
    return 0;
}

// ---------------------------------------------------------------------------
// Help
// ---------------------------------------------------------------------------

bool net_help(std::string_view command) {
    if (command == "remote") {
        std::cout << "usage: vn remote <add|set-url|list|remove> ...\n\n";
        std::cout << "manage native remotes stored in .veins/config\n\n";
        std::cout << "subcommands:\n";
        std::cout << "  add <name> <url> [-key:<name>] [-pin:<hash>]\n";
        std::cout << "                            add a remote\n";
        std::cout << "  set-url <name> <url> [-key:<name>] [-pin:<hash>]\n";
        std::cout << "                            change a remote URL (and "
                     "optionally key/pin)\n";
        std::cout << "  list                      list remotes\n";
        std::cout << "  remove <name>             remove a remote\n\n";
        std::cout << "an empty -key: or -pin: value clears that setting\n\n";
        std::cout << "examples:\n";
        std::cout << "  vn remote add origin veins://127.0.0.1:7419/navid-m/veins2\n";
        std::cout << "  vn remote set-url origin veins://example/repo -key:my-key\n";
        return true;
    }
    if (command == "clone") {
        std::cout << "usage: vn clone <url> [-blobs:<head|none|all>] [-key:<name>] "
                     "[-pin:<sha256>] [path]\n\n";
        std::cout << "clone a repository over file://, ssh://, or veins://\n\n";
        std::cout << "without -key, the key stored by 'vn auth use' is used when "
                     "available\n";
        return true;
    }
    if (command == "fetch") {
        std::cout << "usage: vn fetch [-key:<name>] [<remote>] [path]\n\n";
        std::cout << "fetch new history and chunks from a configured native "
                     "remote\n\n";
        std::cout << "auth falls back to remote.<name>.key, then 'vn auth use'\n";
        return true;
    }
    if (command == "push") {
        std::cout << "usage: vn push [-key:<name>] [<remote>] [<bookmark>] [path]\n\n";
        std::cout << "push a bookmark to a configured native remote\n\n";
        std::cout << "without <bookmark>, the current bookmark is pushed\n";
        std::cout << "auth falls back to remote.<name>.key, then 'vn auth use'\n";
        return true;
    }
    if (command == "serve") {
        std::cout << "usage: vn serve -stdio <repo> [-quota <bytes>]\n";
        std::cout << "       vn serve -listen <addr:port> -root <dir> -tls-cert "
                     "<file> -tls-key <file> [-quota <bytes>]\n\n";
        std::cout << "run the native server over standard input/output or TLS 1.3\n";
        std::cout << "-quota limits stored pack and index bytes per top-level "
                     "namespace\n";
        return true;
    }
    if (command == "key") {
        std::cout << "usage: vn key <generate|list|show> [name]\n\n";
        std::cout << "manage local Ed25519 keys in the user key directory\n";
        return true;
    }
    if (command == "auth") {
        std::cout << "usage: vn auth <use|list|remove> ...\n\n";
        std::cout << "remember which key clone/fetch/push should use\n\n";
        std::cout << "  vn auth use <key> [<host|url>]   set the default or host "
                     "key\n";
        std::cout << "  vn auth list                     show stored key mappings\n";
        std::cout << "  vn auth remove [<host|url>]      remove a mapping\n";
        return true;
    }
    if (command == "access") {
        std::cout << "usage: vn access <add|list|remove|anonymous> ...\n\n";
        std::cout << "manage a served repository's .veins/access policy\n";
        return true;
    }
    if (command == "whoami") {
        std::cout << "usage: vn whoami [<remote>|<url>]\n\n";
        std::cout << "connect to a server and report the granted role and key "
                     "fingerprint\n";
        return true;
    }
    return false;
}

} // namespace vn
