#include <fstream>
#include <iostream>
#include <string>
#include <vector>

#include "evp-encrypt.hpp"
#include "utils.hpp"

int main() {
    const std::string plaintext = "This is a top secret.";
    const std::string target_ct_hex =
        "764aa26b55a4da654df6b19e4bce00f4"
        "ed05e09346fb0e762583cb7da2ac93a2";
    const std::string iv_hex = "aabbccddeeff00998877665544332211";

    Bytes ptext(plaintext.begin(), plaintext.end());
    Bytes target_ct = unhexlify(target_ct_hex);
    Bytes iv_bytes = unhexlify(iv_hex);

    if (iv_bytes.size() != BLOCK_SIZE) {
        std::cerr << "IV length error\n";
        return 1;
    }

    std::ifstream fin("words.txt");
    if (!fin) {
        std::cerr << "Cannot open words.txt\n";
        return 1;
    }

    std::string word;
    while (std::getline(fin, word)) {
        if (!word.empty() && word.back() == '\r') {
            word.pop_back();
        }

        if (word.size() > KEY_SIZE) {
            continue;
        }

        std::string keystr = word;
        keystr.append(KEY_SIZE - keystr.size(), '#');

        Byte key[KEY_SIZE];
        for (size_t i = 0; i < KEY_SIZE; ++i) {
            key[i] = static_cast<Byte>(keystr[i]);
        }

        Bytes c = aes_encrypt(key, iv_bytes.data(), ptext);

        if (c == target_ct) {
            std::cout << "Found key word: " << word << "\n";
            std::cout << "Actual 16-byte key: " << keystr << "\n";
            return 0;
        }
    }

    std::cout << "Key not found.\n";
    return 0;
}
