// tb_mlkem_kg_2e_xsim.v - Stage 2e: verify t_hat = e_hat + sum_j A[i][j]*s_hat[j].
// After ST_M, slots T0,T1 must hold that_0,that_1.
// Golden: kg_c000_that.hex (2 polys x 256 = 512 lines, mod-q).
`timescale 1ns/1ps
module tb_mlkem_kg_2e_xsim;
    reg clk=0, rst_n=0, start_i=0;
    reg [255:0] d_i, z_i=0;
    wire busy_o, done_o;
    reg [3:0] dbg_slot_i=0; reg [7:0] dbg_idx_i=0; wire [11:0] dbg_coeff_o;
    wire [255:0] dbg_rho_o, dbg_sigma_o;

    mlkem_top #(.K(2)) dut (
        .clk(clk), .rst_n(rst_n), .d_i(d_i), .z_i(z_i), .start_i(start_i),
        .busy_o(busy_o), .done_o(done_o),
        .dbg_slot_i(dbg_slot_i), .dbg_idx_i(dbg_idx_i), .dbg_coeff_o(dbg_coeff_o),
        .dbg_rho_o(dbg_rho_o), .dbg_sigma_o(dbg_sigma_o)
    );
    always #5 clk = ~clk;

    localparam [255:0] D_LIT = 256'h2426f1941779574d3f1b163bd57f7e173e229e630ec7f7073bdf365137c4bb6d;

    reg [11:0] gold [0:511];
    reg [3:0]  slot_of [0:1];   // T0,T1
    integer c, p, idx, errors, gi;

    initial begin
        $readmemh("sync_rtl/top/TB/vectors/kg_c000_that.hex", gold);
        slot_of[0]=4'd8; slot_of[1]=4'd9;

        d_i = D_LIT;
        rst_n=0; repeat(4) @(posedge clk); rst_n=1; @(posedge clk);
        start_i=1; @(posedge clk); start_i=0;
        c=0; while(!done_o && c<400000) begin @(posedge clk); c=c+1; end
        if(!done_o) begin $display("FAIL: timeout after %0d cyc", c); $finish; end
        $display("=== Stage 2e: t_hat = e_hat + sum A o s_hat ===  done in %0d cyc", c);

        errors = 0;
        for (p = 0; p < 2; p = p + 1) begin
            for (idx = 0; idx < 256; idx = idx + 1) begin
                dbg_slot_i = slot_of[p];
                dbg_idx_i  = idx[7:0];
                @(posedge clk); @(posedge clk);
                gi = p*256 + idx;
                if (dbg_coeff_o !== gold[gi]) begin
                    if (errors < 8)
                        $display("  MISMATCH slot%0d[%0d]: got=%03x exp=%03x",
                                 slot_of[p], idx, dbg_coeff_o, gold[gi]);
                    errors = errors + 1;
                end
            end
        end
        if (errors == 0) $display("ALL TESTS PASSED (512/512 t_hat coeffs)");
        else             $display("TESTS FAILED: %0d mismatches", errors);
        $finish;
    end
    initial begin #20000000; $display("FAIL: global timeout"); $finish; end
endmodule
