#include "crypto/crypto.h"

#include <blake3.h>

#include <openssl/evp.h>
#include <openssl/rand.h>

#include <cstring>

namespace vn {

namespace {

// The reference implementation hashes the NUL terminator as well, so the
// domain is 12 bytes rather than the 11 characters in the specification.
constexpr char FINGERPRINT_DOMAIN[] = "veins/key/1";

PublicKey key_from_span(Bytes seed) {
    PublicKey out{};
    std::memcpy(out.data(), seed.data(), out.size());
    return out;
}

} // namespace

std::optional<PublicKey> ed25519_public_from_seed(Bytes seed) {
    if (seed.size() != 32)
        return std::nullopt;
    EVP_PKEY* pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, nullptr, seed.data(), 32);
    if (!pkey)
        return std::nullopt;
    PublicKey out{};
    std::size_t len = out.size();
    const int ok = EVP_PKEY_get_raw_public_key(pkey, out.data(), &len);
    EVP_PKEY_free(pkey);
    if (ok != 1 || len != out.size())
        return std::nullopt;
    return out;
}

std::optional<Signature> ed25519_sign(Bytes seed, Bytes message) {
    if (seed.size() != 32)
        return std::nullopt;
    EVP_PKEY* pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_ED25519, nullptr, seed.data(), 32);
    if (!pkey)
        return std::nullopt;
    EVP_MD_CTX* ctx = EVP_MD_CTX_new();
    if (!ctx) {
        EVP_PKEY_free(pkey);
        return std::nullopt;
    }
    Signature out{};
    std::size_t sig_len = out.size();
    bool ok = false;
    if (EVP_DigestSignInit(ctx, nullptr, nullptr, nullptr, pkey) == 1 &&
        EVP_DigestSign(ctx, out.data(), &sig_len, message.data(), message.size()) == 1 &&
        sig_len == out.size()) {
        ok = true;
    }
    EVP_MD_CTX_free(ctx);
    EVP_PKEY_free(pkey);
    if (!ok)
        return std::nullopt;
    return out;
}

bool ed25519_verify(const PublicKey& public_key, Bytes message, Bytes signature) {
    if (signature.size() != 64)
        return false;
    EVP_PKEY* pkey = EVP_PKEY_new_raw_public_key(EVP_PKEY_ED25519, nullptr, public_key.data(),
                                                 public_key.size());
    if (!pkey)
        return false;
    EVP_MD_CTX* ctx = EVP_MD_CTX_new();
    if (!ctx) {
        EVP_PKEY_free(pkey);
        return false;
    }
    bool ok = false;
    if (EVP_DigestVerifyInit(ctx, nullptr, nullptr, nullptr, pkey) == 1 &&
        EVP_DigestVerify(ctx, signature.data(), signature.size(), message.data(), message.size()) ==
            1) {
        ok = true;
    }
    EVP_MD_CTX_free(ctx);
    EVP_PKEY_free(pkey);
    return ok;
}

FingerprintBytes key_fingerprint_bytes(const PublicKey& public_key) {
    blake3_hasher hasher;
    blake3_hasher_init(&hasher);
    blake3_hasher_update(&hasher, FINGERPRINT_DOMAIN, sizeof(FINGERPRINT_DOMAIN));
    blake3_hasher_update(&hasher, public_key.data(), public_key.size());
    std::array<std::uint8_t, 32> digest{};
    blake3_hasher_finalize(&hasher, digest.data(), digest.size());
    FingerprintBytes out{};
    std::memcpy(out.data(), digest.data(), out.size());
    return out;
}

std::string key_fingerprint(const PublicKey& public_key) {
    const auto raw = key_fingerprint_bytes(public_key);
    return base32_text(Bytes(raw.data(), raw.size()));
}

std::string base32_text(Bytes raw) {
    static constexpr char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
    std::string out;
    out.reserve((raw.size() * 8) / 5 + 2);
    std::uint64_t bits = 0;
    std::size_t nbits = 0;
    for (std::uint8_t byte : raw) {
        bits = (bits << 8) | byte;
        nbits += 8;
        while (nbits >= 5) {
            nbits -= 5;
            out.push_back(alphabet[(bits >> nbits) & 31u]);
        }
    }
    if (nbits > 0)
        out.push_back(alphabet[(bits << (5 - nbits)) & 31u]);
    return out;
}

std::string base64url_encode(Bytes raw) {
    static constexpr char alphabet[] =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    std::string out;
    out.reserve((raw.size() * 4) / 3 + 4);
    std::uint32_t acc = 0;
    std::size_t bits = 0;
    for (std::uint8_t byte : raw) {
        acc = (acc << 8) | byte;
        bits += 8;
        while (bits >= 6) {
            bits -= 6;
            out.push_back(alphabet[(acc >> bits) & 63u]);
        }
    }
    if (bits > 0)
        out.push_back(alphabet[(acc << (6 - bits)) & 63u]);
    return out;
}

std::optional<std::vector<std::uint8_t>> base64url_decode(std::string_view text) {
    if (text.empty())
        return std::nullopt;
    static const auto value_of = [](char c) -> int {
        if (c >= 'A' && c <= 'Z')
            return c - 'A';
        if (c >= 'a' && c <= 'z')
            return c - 'a' + 26;
        if (c >= '0' && c <= '9')
            return c - '0' + 52;
        if (c == '-')
            return 62;
        if (c == '_')
            return 63;
        return -1;
    };
    std::vector<std::uint8_t> out;
    out.reserve((text.size() * 6) / 8);
    std::uint32_t acc = 0;
    std::size_t bits = 0;
    for (char c : text) {
        const int value = value_of(c);
        if (value < 0)
            return std::nullopt;
        acc = (acc << 6) | static_cast<std::uint32_t>(value);
        bits += 6;
        if (bits >= 8) {
            bits -= 8;
            out.push_back(static_cast<std::uint8_t>((acc >> bits) & 255u));
        }
    }
    return out;
}

std::string format_public_key(const PublicKey& public_key) {
    return "ed25519:" + base64url_encode(Bytes(public_key.data(), public_key.size()));
}

std::optional<PublicKey> parse_public_key(std::string_view text) {
    constexpr std::string_view prefix = "ed25519:";
    if (!text.starts_with(prefix))
        return std::nullopt;
    auto decoded = base64url_decode(text.substr(prefix.size()));
    if (!decoded || decoded->size() != 32)
        return std::nullopt;
    return key_from_span(Bytes(decoded->data(), decoded->size()));
}

std::vector<std::uint8_t> secure_random(std::size_t count) {
    std::vector<std::uint8_t> out(count);
    if (count != 0 && RAND_bytes(out.data(), static_cast<int>(count)) != 1)
        out.clear();
    return out;
}

} // namespace vn
