// tb_poly_mul_xsim.v - Standard Verilog testbench for poly_mul_sync targeting Vivado xsim
//
// Reads test vectors from a hex file using $readmemh.
// Each line is a single hex number encoding 512 coefficient values:
//   - bits [6143:3072]: 256 x 12-bit polynomial A coefficients
//   - bits [3071:0]:    256 x 12-bit polynomial B coefficients
//   - Total: 1536 hex chars per line, NO spaces
//
// Drives poly_mul_sync, streams in 256 A+B coefficient pairs via valid/ready,
// waits for valid_o output, streams out 256 result coefficients,
// and writes "RESULT: INDEX COEFF_HEX" to the output file.
//
// poly_mul_sync FSM: IDLE → LOAD → COMP_CALC → COMP_C0 → COMP_C1 → ... → DONE → IDLE
// valid_o is asserted during COMP_C0 and COMP_C1 states.
//
// Parameters:
//   VECTOR_FILE - path to input hex file (default: "vectors/poly_mul_input.hex")
//   RESULT_FILE - path to output file    (default: "vectors/poly_mul_result.hex")
//
// Usage:
//   xvlog -sv barrett_mul.v basecase_mul.v poly_mul_zeta_rom.v poly_mul_sync.v tb_poly_mul_xsim.v
//   xelab tb_poly_mul_xsim -s tb_poly_mul_xsim
//   xsim tb_poly_mul_xsim -R

`timescale 1ns / 1ps

module tb_poly_mul_xsim;

    // ================================================================
    // Parameters
    // ================================================================
    parameter VECTOR_FILE   = "sync_rtl/poly_mul/TB/vectors/poly_mul_input.hex";
    parameter RESULT_FILE   = "sync_rtl/poly_mul/TB/vectors/poly_mul_result.hex";
    parameter MAX_VECTORS   = 64;
    parameter N_COEFFS      = 256;
    parameter TIMEOUT_CYCLES= 100000;

    // ================================================================
    // DUT signals
    // ================================================================
    reg              clk;
    reg              rst_n;
    reg  [11:0]      coeff_a_in;
    reg  [11:0]      coeff_b_in;
    reg              valid_i;
    wire             ready_o;
    wire [11:0]      coeff_out;
    wire             valid_o;
    reg              ready_i;

    // ================================================================
    // DUT instantiation
    // ================================================================
    poly_mul_sync u_dut (
        .clk        (clk),
        .rst_n      (rst_n),
        .coeff_a_in (coeff_a_in),
        .coeff_b_in (coeff_b_in),
        .valid_i    (valid_i),
        .ready_o    (ready_o),
        .coeff_out  (coeff_out),
        .valid_o    (valid_o),
        .ready_i    (ready_i)
    );

    // ================================================================
    // Clock generation: 100 MHz (10 ns period)
    // ================================================================
    initial clk = 1'b0;
    always #5 clk = ~clk;

    // ================================================================
    // Vector memory (loaded by $readmemh)
    // 6144 bits per word:
    //   bits [6143:3072]: 256 x 12-bit A coefficients (A[0] at MSB)
    //   bits [3071:0]:    256 x 12-bit B coefficients (B[0] at MSB of lower half)
    // ================================================================
    reg [6143:0] vector_mem [0:MAX_VECTORS-1];
    integer      vec_count;
    integer      idx;
    integer      ci;
    integer      cycle_count;
    integer      result_fd;

    // Test result tracking
    integer      pass_count;
    integer      fail_count;

    // Temporary storage for coefficients
    reg [11:0]   a_coeffs [0:N_COEFFS-1];
    reg [11:0]   b_coeffs [0:N_COEFFS-1];
    reg [11:0]   output_coeffs [0:N_COEFFS-1];

    // ================================================================
    // Hex-to-ASCII conversion helper
    // ================================================================
    function [7:0] nibble_to_ascii;
        input [3:0] nibble;
        begin
            if (nibble < 4'd10)
                nibble_to_ascii = 8'h30 + {4'd0, nibble};  // '0'-'9'
            else
                nibble_to_ascii = 8'h41 + ({4'd0, nibble} - 4'd10); // 'A'-'F'
        end
    endfunction

    // ================================================================
    // Main test sequence
    // ================================================================
    initial begin
        // Count loaded vectors
        vec_count = 0;

        // Load vectors from hex file
        $readmemh(VECTOR_FILE, vector_mem);

        // Count entries (XSim leaves unloaded entries as 6144'hX)
        begin
            integer found_end;
            found_end = 0;
            for (idx = 0; idx < MAX_VECTORS; idx = idx + 1) begin
                if (!found_end && (vector_mem[idx] === 6144'hx ||
                                   vector_mem[idx] === 6144'hz))
                    found_end = 1;
                else if (!found_end)
                    vec_count = vec_count + 1;
            end
        end

        if (vec_count == 0) begin
            $display("ERROR: No vectors loaded from %s", VECTOR_FILE);
            $display("       Check that the file exists and format is correct.");
            $display("       Each line: 1536 hex chars (768 hex A + 768 hex B)");
            $finish;
        end

        $display("INFO: Loaded %0d test vectors from %s", vec_count, VECTOR_FILE);

        // Open result file
        result_fd = $fopen(RESULT_FILE, "w");
        if (result_fd == 0) begin
            $display("ERROR: Cannot open result file: %s", RESULT_FILE);
            $finish;
        end

        // Initialize DUT inputs
        coeff_a_in <= 12'd0;
        coeff_b_in <= 12'd0;
        valid_i    <= 1'b0;
        ready_i    <= 1'b1;  // always ready to accept output

        // Reset sequence: rst_n low for 3 cycles, then high
        rst_n <= 1'b0;
        repeat (3) @(posedge clk);
        rst_n <= 1'b1;
        @(posedge clk);

        pass_count = 0;
        fail_count = 0;

        // ============================================================
        // Process each vector
        // ============================================================
        for (idx = 0; idx < vec_count; idx = idx + 1) begin
            begin
                integer out_idx;
                integer input_ok;

                // Extract A and B coefficients from vector memory
                //
                // Memory layout (A in MSB half, B in LSB half):
                //   A[0]   → bits [6143:6132]
                //   A[1]   → bits [6131:6120]
                //   ...
                //   A[255] → bits [3083:3072]
                //   B[0]   → bits [3071:3060]
                //   B[1]   → bits [3059:3048]
                //   ...
                //   B[255] → bits [11:0]
                //
                // Formula: coeff[i] = vector_mem[(N-1-i)*12+11+offset : (N-1-i)*12+offset]
                //   A: offset = N*12 = 3072
                //   B: offset = 0
                for (ci = 0; ci < N_COEFFS; ci = ci + 1) begin
                    a_coeffs[ci] = vector_mem[idx][(N_COEFFS-1-ci)*12 + N_COEFFS*12 +: 12];
                    b_coeffs[ci] = vector_mem[idx][(N_COEFFS-1-ci)*12 +: 12];
                end

                $display("INFO: Vector %0d", idx);

                input_ok = 1;

                // ----------------------------------------------------
                // LOAD phase: stream in 256 A+B coefficient pairs
                // ----------------------------------------------------
                for (ci = 0; ci < N_COEFFS && input_ok; ci = ci + 1) begin
                    // Wait for ready_o before driving next input
                    cycle_count = 0;
                    while (!ready_o && cycle_count < TIMEOUT_CYCLES) begin
                        @(posedge clk);
                        cycle_count = cycle_count + 1;
                    end
                    if (cycle_count >= TIMEOUT_CYCLES) begin
                        $display("ERROR: Timeout waiting for ready_o (input ci=%0d) on vector %0d",
                                 ci, idx);
                        fail_count = fail_count + 1;
                        input_ok = 0;
                    end else begin
                        coeff_a_in <= a_coeffs[ci];
                        coeff_b_in <= b_coeffs[ci];
                        valid_i    <= 1'b1;
                        @(posedge clk);
                        valid_i    <= 1'b0;
                    end
                end

                if (!input_ok) begin
                    // Skip output reading for this failed vector
                    @(posedge clk);
                end else begin
                    // ----------------------------------------------------
                    // OUTPUT phase: wait for valid_o and stream out results
                    // poly_mul_sync enters COMP_CALC→COMP_C0 state after LOAD.
                    // valid_o is asserted during COMP_C0 and COMP_C1.
                    // There may be cycles with valid_o=0 between outputs
                    // (during COMP_CALC transitions).
                    // ----------------------------------------------------
                    out_idx = 0;
                    while (out_idx < N_COEFFS) begin
                        // Wait for valid_o
                        cycle_count = 0;
                        while (!valid_o && cycle_count < TIMEOUT_CYCLES) begin
                            @(posedge clk);
                            cycle_count = cycle_count + 1;
                        end

                        if (cycle_count >= TIMEOUT_CYCLES) begin
                            $display("ERROR: Timeout waiting for valid_o (output %0d) on vector %0d",
                                     out_idx, idx);
                            fail_count = fail_count + 1;
                            out_idx = N_COEFFS;  // break out
                        end else begin
                            // Capture output coefficient
                            output_coeffs[out_idx] = coeff_out;
                            out_idx = out_idx + 1;
                            @(posedge clk);  // ready_i=1, consume output
                        end
                    end

                    pass_count = pass_count + 1;

                    // Write result to output file
                    // Format: "RESULT: INDEX COEFF_HEX"
                    $fwrite(result_fd, "RESULT: %0d ", idx);
                    // Write all 256 output coeffs as hex (3 chars each = 768 total)
                    begin
                        integer oi;
                        reg [3:0] nib;
                        for (oi = 0; oi < N_COEFFS; oi = oi + 1) begin
                            nib = output_coeffs[oi][11:8];
                            $fwrite(result_fd, "%c", nibble_to_ascii(nib));
                            nib = output_coeffs[oi][7:4];
                            $fwrite(result_fd, "%c", nibble_to_ascii(nib));
                            nib = output_coeffs[oi][3:0];
                            $fwrite(result_fd, "%c", nibble_to_ascii(nib));
                        end
                    end
                    $fwrite(result_fd, "\n");

                    // Wait for DUT to return to IDLE before next vector
                    // The DUT goes to S_DONE then S_IDLE after all outputs
                    cycle_count = 0;
                    while (!ready_o && cycle_count < 1000) begin
                        @(posedge clk);
                        cycle_count = cycle_count + 1;
                    end
                end

                // Extra cycle before next vector
                @(posedge clk);
            end  // inner begin block
        end

        // ============================================================
        // Summary
        // ============================================================
        $fclose(result_fd);

        $display("========================================");
        $display("TEST COMPLETE");
        $display("  Total vectors: %0d", vec_count);
        $display("  Passed:        %0d", pass_count);
        $display("  Failed:        %0d", fail_count);
        $display("  Results written to: %s", RESULT_FILE);
        $display("========================================");

        $finish;
    end

    // ================================================================
    // Timeout watchdog
    // ================================================================
    initial begin
        // TIMEOUT_CYCLES * 10ns per cycle * 10x margin
        #(TIMEOUT_CYCLES * 10 * 10);
        $display("FATAL: Global simulation timeout reached");
        $finish;
    end

endmodule
