// tb_sample_cbd.cpp - Verilator C++ testbench for sample_cbd_sync
//
// Reads test vectors from +VECTOR_FILE= plusarg.
// Format: "SEED_HEX NONCE_HEX ETA"
//   SEED_HEX: 64 hex chars (256-bit seed, MSB-first)
//   NONCE_HEX: 2 hex chars (8-bit nonce)
//   ETA: "2" or "3" (decimal)
//
// Drives DUT with seed, nonce, eta. Waits for valid_o, collects 256
// coefficients. Prints "RESULT: COEFF_HEX\n" for each coefficient.
//
// Clock: 10ns period. Reset: 2 cycles.
// Timeout: 500000 cycles.

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cstdlib>
#include <cstring>
#include <cstdint>
#include "Vsample_cbd_sync.h"
#include "verilated.h"

#define CLK_PERIOD_NS     10.0
#define TIMEOUT_CYCLES    500000

static vluint64_t main_time = 0;

double sc_time_stamp() {
    return main_time;
}

// Toggle clock: both edges + eval (one full cycle)
static void posedge(Vsample_cbd_sync* dut) {
    dut->clk = !dut->clk;
    main_time += (vluint64_t)(CLK_PERIOD_NS / 2.0);
    dut->eval();
    dut->clk = !dut->clk;
    main_time += (vluint64_t)(CLK_PERIOD_NS / 2.0);
    dut->eval();
}

static int hex_char_to_nibble(char c) {
    if (c >= '0' && c <= '9') return c - '0';
    if (c >= 'A' && c <= 'F') return c - 'A' + 10;
    if (c >= 'a' && c <= 'f') return c - 'a' + 10;
    return 0;
}

// Parse hex string (MSB-first) into 8 x 32-bit words for 256-bit seed.
// Word 0 = bits[31:0], word 7 = bits[255:224].
// Hex string: leftmost char = most significant nibble (bits 255:252).
static void hex_to_256(const std::string& hex, uint32_t data_words[8]) {
    for (int w = 0; w < 8; w++) data_words[w] = 0;

    int len = (int)hex.length();
    int nibble_idx = 0;
    for (int i = len - 1; i >= 0; i--) {
        char c = hex[i];
        if (c == ' ' || c == '\t') continue;
        int nib = hex_char_to_nibble(c);
        int word_idx = nibble_idx / 8;
        int shift    = (nibble_idx % 8) * 4;
        if (word_idx < 8) {
            data_words[word_idx] |= ((uint32_t)nib << shift);
        }
        nibble_idx++;
    }
}

// Parse 2-char hex string into an 8-bit value.
// "FF" → 0xFF, "0A" → 0x0A.
static uint8_t hex_to_8(const std::string& hex) {
    int val = 0;
    for (size_t i = 0; i < hex.length(); i++) {
        val = (val << 4) | hex_char_to_nibble(hex[i]);
    }
    return (uint8_t)(val & 0xFF);
}

int main(int argc, char** argv) {
    Verilated::commandArgs(argc, argv);

    // Parse +VECTOR_FILE= plusarg
    const char* vector_file = NULL;
    for (int i = 1; i < argc; i++) {
        std::string arg(argv[i]);
        if (arg.rfind("+VECTOR_FILE=", 0) == 0) {
            vector_file = argv[i] + 13;
        }
    }

    if (!vector_file) {
        std::cerr << "ERROR: +VECTOR_FILE= not specified" << std::endl;
        return 1;
    }

    std::ifstream infile(vector_file);
    if (!infile.is_open()) {
        std::cerr << "ERROR: Cannot open vector file: " << vector_file << std::endl;
        return 1;
    }

    // Instantiate DUT
    Vsample_cbd_sync* dut = new Vsample_cbd_sync;

    // Initialize
    dut->clk     = 0;
    dut->rst_n   = 0;
    for (int w = 0; w < 8; w++) dut->seed_i[w] = 0;
    dut->nonce_i = 0;
    dut->eta_i   = 0;
    dut->valid_i = 0;
    dut->ready_i = 0;

    // Reset: 2 full cycles
    for (int i = 0; i < 2; i++) posedge(dut);
    dut->rst_n = 1;

    // Consumer always ready
    dut->ready_i = 1;

    std::string line;
    vluint64_t cycle = 0;
    int vec_count = 0;
    int total_coeff_count = 0;

    while (std::getline(infile, line)) {
        if (line.empty() || line[0] == '#') continue;

        // Parse: SEED_HEX NONCE_HEX ETA
        std::istringstream iss(line);
        std::string seed_hex, nonce_hex;
        int eta_val;
        if (!(iss >> seed_hex >> nonce_hex >> eta_val)) continue;
        if (seed_hex.length() < 64) continue;

        // Set seed_i (256 bits)
        uint32_t seed_words[8];
        hex_to_256(seed_hex, seed_words);
        for (int w = 0; w < 8; w++) dut->seed_i[w] = seed_words[w];

        // Set nonce_i (8 bits)
        dut->nonce_i = hex_to_8(nonce_hex);

        // Set eta_i (2'd2 or 2'd3)
        dut->eta_i = (eta_val == 3) ? 3 : 2;

        // Assert valid_i for one cycle
        dut->valid_i = 1;
        posedge(dut);
        cycle++;
        dut->valid_i = 0;

        // Wait for 256 coefficients
        int coeffs_collected = 0;
        bool timed_out = false;

        while (coeffs_collected < 256) {
            posedge(dut);
            cycle++;

            if (cycle > TIMEOUT_CYCLES) {
                std::cerr << "ERROR: Timeout waiting for coeffs (vec "
                          << vec_count << ", got " << coeffs_collected
                          << "/256)" << std::endl;
                timed_out = true;
                break;
            }

            if (dut->valid_o && dut->ready_i) {
                // Read 12-bit coefficient and print
                uint32_t coeff = dut->coeff_o & 0xFFF;
                printf("RESULT: %03X\n", coeff);
                coeffs_collected++;
                total_coeff_count++;
            }
        }

        if (timed_out) {
            goto done;
        }

        // Wait for DUT to return to IDLE before next vector
        int wait_cycles = 0;
        while (!dut->ready_o && wait_cycles < 100) {
            posedge(dut);
            cycle++;
            wait_cycles++;
        }

        vec_count++;
    }

done:
    infile.close();
    delete dut;

    if (vec_count == 0) {
        std::cerr << "ERROR: No vectors processed" << std::endl;
        return 1;
    }

    return 0;
}
