// tb_mlkem_kg_2f_xsim.v - Stage 2f: verify byteEncode12 -> ek (800B), dk_pke (768B).
// ek = byteEncode12(t_hat[0..1]) || rho ; dk_pke = byteEncode12(s_hat[0..1]).
// Golden: c000_ek.hex (single 1600-hex line), c000_dkpke.hex (1536-hex line).
`timescale 1ns/1ps
module tb_mlkem_kg_2f_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;
    reg dbg_byte_sel_i=0; reg [9:0] dbg_byte_idx_i=0; wire [7:0] dbg_byte_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_byte_sel_i(dbg_byte_sel_i), .dbg_byte_idx_i(dbg_byte_idx_i), .dbg_byte_o(dbg_byte_o),
        .dbg_rho_o(dbg_rho_o), .dbg_sigma_o(dbg_sigma_o)
    );
    always #5 clk = ~clk;

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

    // golden bytes loaded as memories: 1 byte per entry
    reg [7:0] ek_gold  [0:799];
    reg [7:0] dkp_gold [0:767];
    integer c, i, errors;

    initial begin
        $readmemh("sync_rtl/top/TB/vectors/c000_ek_bytes.hex", ek_gold);
        $readmemh("sync_rtl/top/TB/vectors/c000_dkpke_bytes.hex", dkp_gold);

        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<500000) begin @(posedge clk); c=c+1; end
        if(!done_o) begin $display("FAIL: timeout after %0d cyc", c); $finish; end
        $display("=== Stage 2f: byteEncode12 -> ek/dk_pke ===  done in %0d cyc", c);

        errors = 0;
        // ek: 800 bytes (sel=0)
        dbg_byte_sel_i = 1'b0;
        for (i = 0; i < 800; i = i + 1) begin
            dbg_byte_idx_i = i[9:0];
            @(posedge clk); @(posedge clk);
            if (dbg_byte_o !== ek_gold[i]) begin
                if (errors < 8) $display("  EK MISMATCH[%0d]: got=%02x exp=%02x", i, dbg_byte_o, ek_gold[i]);
                errors = errors + 1;
            end
        end
        // dk_pke: 768 bytes (sel=1)
        dbg_byte_sel_i = 1'b1;
        for (i = 0; i < 768; i = i + 1) begin
            dbg_byte_idx_i = i[9:0];
            @(posedge clk); @(posedge clk);
            if (dbg_byte_o !== dkp_gold[i]) begin
                if (errors < 8) $display("  DKP MISMATCH[%0d]: got=%02x exp=%02x", i, dbg_byte_o, dkp_gold[i]);
                errors = errors + 1;
            end
        end
        if (errors == 0) $display("ALL TESTS PASSED (ek 800B + dk_pke 768B exact)");
        else             $display("TESTS FAILED: %0d byte mismatches", errors);
        $finish;
    end
    initial begin #30000000; $display("FAIL: global timeout"); $finish; end
endmodule
