// retroDE_ps2 — tb_gs_clut_load_cld_modes (Ch101)
//
// Locks the conditional CLD-mode policy in clut_loader_stub:
//   CLD=0 → never load
//   CLD=1 → always load (full 256 entries)
//   CLD=2 → load only when CBP changed since last load
//   CLD=3 → load when CBP, CPSM, or CSA changed since last load
//   CLD=4 → always load (Ch102; partial 16-entry CSA window —
//          this TB only verifies the trigger fires; the
//          write-range correctness is covered by
//          tb_gs_clut_load_csa_window)
//   CLD ∈ {5..7} → silently no-op at this scope
//
// The test counts loader-start events (rising edge of
// `loader_busy`) across a sequence of TEX0_1 writes that walk
// through each CLD mode. VRAM contents don't matter — we only
// care whether the loader fires.
//
// Phases:
//   Phase 1 — CLD=0, CBP=4, CPSM=PSMCT32. Expect: NO load.
//   Phase 2 — CLD=1, CBP=4. Expect: load #1. prev_cbp ← 4.
//   Phase 3 — CLD=2, CBP=4 (unchanged). Expect: NO load.
//   Phase 4 — CLD=2, CBP=8. Expect: load #2. prev_cbp ← 8.
//   Phase 5 — CLD=3, CBP=8 / CPSM=0 / CSA=0 (all unchanged from
//             phase 4). Expect: NO load.
//   Phase 6 — CLD=3, CBP=8 / CPSM=0 / CSA=2 (CSA changed).
//             Expect: load #3.
//   Phase 7  — CLD=3, CBP=8 / CPSM=2 / CSA=2 (CPSM changed).
//              Expect: load #4.
//   Phase 7b — CLD=3, CBP=12 (CBP-arm of CLD=3 isolated).
//              Expect: load #5.
//   Phase 8  — CLD=4, partial CSA-window load (Ch102) — fires
//              every time. Expect: load #6. (Write-range
//              correctness is locked by tb_gs_clut_load_csa_window.)
//   Phase 8b — CLD ∈ {5, 6, 7} reserved no-op. Expect: NO load.
//   Phase 9  — CLD=1 (always) regardless of state. Expect: load #7.

`timescale 1ns/1ps

module tb_gs_clut_load_cld_modes;

    logic clk;
    logic rst_n;
    initial clk = 1'b0;
    always #5 clk = ~clk;

    logic        gif_reg_wr_en;
    logic [7:0]  gif_reg_num;
    logic [63:0] gif_reg_data;
    logic        priv_reg_wr_en;
    logic [15:0] priv_reg_wr_addr;
    logic [63:0] priv_reg_wr_data;

    logic [7:0]          bg_r, bg_g, bg_b;
    logic [63:0]         pmode_q, dispfb1_q, display1_q;
    logic [63:0]         prim_q, rgbaq_q, xyz2_q, xyzf2_q, frame_1_q, zbuf_1_q;
    logic [63:0]         tex0_1_q;
    logic [13:0]         tex0_1_cbp_q;
    logic [3:0]          tex0_1_cpsm_q;
    logic                tex0_1_csm_q;
    logic [4:0]          tex0_1_csa_q;
    logic [2:0]          tex0_1_cld_q;
    logic                tex0_1_wr_q;
    logic                prim_complete;
    logic [31:0]         prim_complete_count;
    logic [63:0]         prim_v0_q, prim_v1_q, prim_v2_q;
    logic [63:0]         prim_color_q;
    logic [63:0]         prim_color_v0_q, prim_color_v1_q, prim_color_v2_q;
    trace_pkg::vertex_t  prim_v0_decoded_q, prim_v1_decoded_q, prim_v2_decoded_q;
    trace_pkg::color_t   prim_v0_color_decoded_q, prim_v1_color_decoded_q, prim_v2_color_decoded_q;
    logic                pixel_emit;
    logic [31:0]         pixel_emit_count;
    logic [11:0]         pixel_x_q, pixel_y_q;
    logic [63:0]         pixel_color_q;
    logic [8:0]          pixel_fbp_q;
    logic [5:0]          pixel_fbw_q, pixel_psm_q;
    logic [31:0]         pixel_fb_addr_q;
    logic                raster_pixel_emit;
    logic [31:0]         raster_pixel_emit_count;
    logic [11:0]         raster_pixel_x_q, raster_pixel_y_q;
    logic [63:0]         raster_pixel_color_q;
    logic [31:0]         raster_pixel_fb_addr_q;
    logic [3:0]          raster_pixel_be_q;
    logic [5:0]          raster_pixel_psm_q;
    logic                raster_active;
    logic                raster_overflow;
    logic                raster_degenerate;
    logic                gs_ev_valid;
    trace_pkg::subsys_e  gs_ev_subsys;
    trace_pkg::event_e   gs_ev_event;
    logic [63:0]         gs_ev_arg0, gs_ev_arg1, gs_ev_arg2, gs_ev_arg3;
    logic [31:0]         gs_ev_flags;

    gs_stub u_gs (
        .clk(clk), .rst_n(rst_n),
        .reg_wr_en  (priv_reg_wr_en),
        .reg_wr_addr(priv_reg_wr_addr),
        .reg_wr_data(priv_reg_wr_data),
        .gif_reg_wr_en(gif_reg_wr_en),
        .gif_reg_num(gif_reg_num),
        .gif_reg_data(gif_reg_data),
        .bg_r(bg_r), .bg_g(bg_g), .bg_b(bg_b),
        .pmode_q(pmode_q), .dispfb1_q(dispfb1_q), .display1_q(display1_q),
        .prim_q(prim_q), .rgbaq_q(rgbaq_q),
        .xyz2_q(xyz2_q), .xyzf2_q(xyzf2_q),
        .frame_1_q(frame_1_q), .zbuf_1_q(zbuf_1_q),
        .tex0_1_q(tex0_1_q),
        .tex0_1_cbp_q(tex0_1_cbp_q),
        .tex0_1_cpsm_q(tex0_1_cpsm_q),
        .tex0_1_csm_q(tex0_1_csm_q),
        .tex0_1_csa_q(tex0_1_csa_q),
        .tex0_1_cld_q(tex0_1_cld_q),
        .tex0_1_wr_q(tex0_1_wr_q),
        .prim_complete(prim_complete),
        .prim_complete_count(prim_complete_count),
        .prim_v0_q(prim_v0_q), .prim_v1_q(prim_v1_q), .prim_v2_q(prim_v2_q),
        .prim_color_q(prim_color_q),
        .prim_color_v0_q(prim_color_v0_q),
        .prim_color_v1_q(prim_color_v1_q),
        .prim_color_v2_q(prim_color_v2_q),
        .prim_v0_decoded_q(prim_v0_decoded_q),
        .prim_v1_decoded_q(prim_v1_decoded_q),
        .prim_v2_decoded_q(prim_v2_decoded_q),
        .prim_v0_color_decoded_q(prim_v0_color_decoded_q),
        .prim_v1_color_decoded_q(prim_v1_color_decoded_q),
        .prim_v2_color_decoded_q(prim_v2_color_decoded_q),
        .pixel_emit(pixel_emit),
        .pixel_emit_count(pixel_emit_count),
        .pixel_x_q(pixel_x_q), .pixel_y_q(pixel_y_q),
        .pixel_color_q(pixel_color_q),
        .pixel_fbp_q(pixel_fbp_q),
        .pixel_fbw_q(pixel_fbw_q),
        .pixel_psm_q(pixel_psm_q),
        .pixel_fb_addr_q(pixel_fb_addr_q),
        .raster_pixel_emit(raster_pixel_emit),
        .raster_pixel_emit_count(raster_pixel_emit_count),
        .raster_pixel_x_q(raster_pixel_x_q),
        .raster_pixel_y_q(raster_pixel_y_q),
        .raster_pixel_color_q(raster_pixel_color_q),
        .raster_pixel_fb_addr_q(raster_pixel_fb_addr_q),
        .raster_pixel_be_q(raster_pixel_be_q),
        .raster_pixel_psm_q(raster_pixel_psm_q),
        .raster_active(raster_active),
        .raster_overflow(raster_overflow),
        .raster_degenerate(raster_degenerate),
        .ev_valid(gs_ev_valid),
        .ev_subsys(gs_ev_subsys),
        .ev_event(gs_ev_event),
        .ev_arg0(gs_ev_arg0), .ev_arg1(gs_ev_arg1),
        .ev_arg2(gs_ev_arg2), .ev_arg3(gs_ev_arg3),
        .ev_flags(gs_ev_flags)
    );

    // VRAM: contents irrelevant for this policy test, but the
    // loader needs a real read port to drive while it walks.
    logic [31:0] vram_raddr;
    logic [31:0] vram_rdata;
    logic [31:0] vram_raddr2;
    logic [31:0] vram_rdata2;

    vram_stub #(.BYTES(8192)) u_vram (
        .clk(clk), .rst_n(rst_n),
        .write_en  (1'b0),
        .write_addr(32'd0),
        .write_data(32'd0),
        .write_be  (4'b0000),
        .write_mask(32'hFFFF_FFFF),
        .read_addr (vram_raddr),
        .read_data (vram_rdata),
        .read2_addr(vram_raddr2),
        .read2_data(vram_rdata2)
    );

    // CLUT — the loader writes here when it fires.
    logic        clut_we;
    logic [7:0]  clut_widx;
    logic [31:0] clut_wdata;

    clut_stub u_clut (
        .clk(clk), .rst_n(rst_n),
        .write_en  (clut_we),
        .write_idx (clut_widx),
        .write_data(clut_wdata),
        .read_idx  (8'd0),
        .read_data ()
    );

    logic loader_busy;

    clut_loader_stub u_loader (
        .clk(clk), .rst_n(rst_n),
        .tex0_wr_pulse  (tex0_1_wr_q),
        .tex0_cbp       (tex0_1_cbp_q),
        .tex0_cpsm      (tex0_1_cpsm_q),
        .tex0_csm       (tex0_1_csm_q),
        .tex0_csa       (tex0_1_csa_q),
        .tex0_cld       (tex0_1_cld_q),
        .vram_read_addr (vram_raddr2),
        .vram_read_data (vram_rdata2),
        .clut_write_en  (clut_we),
        .clut_write_idx (clut_widx),
        .clut_write_data(clut_wdata),
        .load_busy      (loader_busy)
    );

    assign vram_raddr = 32'd0;

    // Count load-start events: rising edge of loader_busy.
    int  load_start_count;
    bit  loader_busy_d;
    initial begin
        load_start_count = 0;
        loader_busy_d    = 1'b0;
    end
    always_ff @(posedge clk) begin
        if (rst_n) begin
            loader_busy_d <= loader_busy;
            if (loader_busy && !loader_busy_d) begin
                load_start_count <= load_start_count + 1;
            end
        end
    end

    int errors;
    initial errors = 0;

    task automatic step_drive(input logic        wr_en,
                              input logic [7:0]  num,
                              input logic [63:0] data);
        @(negedge clk);
        gif_reg_wr_en = wr_en;
        gif_reg_num   = num;
        gif_reg_data  = data;
        @(posedge clk);
    endtask

    task automatic drive_reg(input logic [7:0] num, input logic [63:0] data);
        step_drive(1'b1, num, data);
    endtask

    task automatic drive_idle();
        step_drive(1'b0, 8'd0, 64'd0);
    endtask

    function automatic logic [63:0] tex0_pack(
        input logic [13:0] cbp,
        input logic [3:0]  cpsm,
        input logic        csm,
        input logic [4:0]  csa,
        input logic [2:0]  cld);
        logic [63:0] v;
        v = 64'd0;
        v[50:37] = cbp;
        v[54:51] = cpsm;
        v[55]    = csm;
        v[60:56] = csa;
        v[63:61] = cld;
        return v;
    endfunction

    // Drive a TEX0_1 write and wait long enough that any
    // resulting load completes (256 cycles) plus margin. Whether
    // the load actually fired or not, after this returns the
    // loader is back in S_IDLE.
    task automatic drive_tex0_and_wait(input logic [13:0] cbp,
                                       input logic [3:0]  cpsm,
                                       input logic        csm,
                                       input logic [4:0]  csa,
                                       input logic [2:0]  cld);
        drive_reg(8'h06, tex0_pack(cbp, cpsm, csm, csa, cld));
        drive_idle();
        repeat (300) @(posedge clk);
    endtask

    task automatic check_count(input int     expected,
                               input string  tag);
        if (load_start_count != expected) begin
            $error("[%s] load_start_count=%0d (expected %0d)",
                   tag, load_start_count, expected);
            errors = errors + 1;
        end
    endtask

    initial begin
        rst_n            = 1'b0;
        gif_reg_wr_en    = 1'b0;
        gif_reg_num      = 8'd0;
        gif_reg_data     = 64'd0;
        priv_reg_wr_en   = 1'b0;
        priv_reg_wr_addr = 16'd0;
        priv_reg_wr_data = 64'd0;

        repeat (4) @(posedge clk);
        rst_n = 1'b1;
        repeat (2) @(posedge clk);

        // Phase 1 — CLD=0 must never load.
        drive_tex0_and_wait(14'd4, 4'd0, 1'b1, 5'd0, 3'd0);
        check_count(0, "phase1 CLD=0 no-load");

        // Phase 2 — CLD=1 always loads. Count → 1.
        drive_tex0_and_wait(14'd4, 4'd0, 1'b1, 5'd0, 3'd1);
        check_count(1, "phase2 CLD=1 always");

        // Phase 3 — CLD=2 with CBP unchanged (still 4): no load.
        drive_tex0_and_wait(14'd4, 4'd0, 1'b1, 5'd0, 3'd2);
        check_count(1, "phase3 CLD=2 same CBP no-load");

        // Phase 4 — CLD=2 with CBP changed (4 → 8): load. Count → 2.
        drive_tex0_and_wait(14'd8, 4'd0, 1'b1, 5'd0, 3'd2);
        check_count(2, "phase4 CLD=2 CBP changed");

        // Phase 5 — CLD=3 with CBP/CPSM/CSA all unchanged from
        // phase 4 (CBP=8/CPSM=0/CSA=0): no load.
        drive_tex0_and_wait(14'd8, 4'd0, 1'b1, 5'd0, 3'd3);
        check_count(2, "phase5 CLD=3 nothing changed no-load");

        // Phase 6 — CLD=3 with CSA changed (0 → 2): load. Count → 3.
        drive_tex0_and_wait(14'd8, 4'd0, 1'b1, 5'd2, 3'd3);
        check_count(3, "phase6 CLD=3 CSA changed");

        // Phase 7 — CLD=3 with CPSM changed (PSMCT32 → PSMCT16):
        // load. Count → 4.
        drive_tex0_and_wait(14'd8, 4'd2, 1'b1, 5'd2, 3'd3);
        check_count(4, "phase7 CLD=3 CPSM changed");

        // Phase 7b — CLD=3 with CBP changed (8 → 12), CPSM and
        // CSA matching the post-phase-7 prev_*: load. Count → 5.
        // Isolates the CBP-arm of CLD=3 change detection (the
        // earlier CLD=2 CBP-changed phase didn't exercise CLD=3).
        drive_tex0_and_wait(14'd12, 4'd2, 1'b1, 5'd2, 3'd3);
        check_count(5, "phase7b CLD=3 CBP changed");

        // Phase 8 — CLD=4 (partial CSA-window load) now fires
        // (Ch102) — it always loads 16 entries at the CSA window.
        // Count → 6. The actual write-range correctness is
        // covered by tb_gs_clut_load_csa_window; here we just
        // verify the trigger fires.
        drive_tex0_and_wait(14'd16, 4'd0, 1'b1, 5'd0, 3'd4);
        check_count(6, "phase8 CLD=4 partial CSA-window fires");

        // Phase 8b — CLD ∈ {5, 6, 7} are reserved/edge cases at
        // this scope and must silently no-op. Drive each with
        // values that WOULD trigger CLD=1's unconditional path;
        // load_start_count must stay at 6.
        for (int cld_v = 5; cld_v <= 7; cld_v++) begin
            logic [2:0] cld_3;
            cld_3 = cld_v[2:0];
            drive_tex0_and_wait(14'd16, 4'd0, 1'b1, 5'd0, cld_3);
            check_count(6, "phase8b CLD>=5 reserved no-load");
        end

        // Phase 9 — CLD=1 always loads regardless of state.
        // Count → 7.
        drive_tex0_and_wait(14'd16, 4'd0, 1'b1, 5'd0, 3'd1);
        check_count(7, "phase9 CLD=1 forced");

        $display("[tb_gs_clut_load_cld_modes] total load_start_count=%0d (expected 7)",
                 load_start_count);

        if (errors == 0) $display("[tb_gs_clut_load_cld_modes] PASS");
        else             $display("[tb_gs_clut_load_cld_modes] FAIL");
        $finish;
    end

    initial begin
        #5000000;
        $error("[tb_gs_clut_load_cld_modes] timeout");
        $finish;
    end

endmodule : tb_gs_clut_load_cld_modes
