// EP08: 32 KiB scratch BRAM, true dual port, full-word writes.
// Port A: CPU read/write when the DMA is idle, or DMA write when it is active.
// Port B: DMA read.
// The test firmware performs only 32-bit word stores to the scratch RAM, so the
// byte-enable inputs are intentionally not used here. CPU and DMA never access
// the RAM in the same cycle: the top level gates CPU requests with dma_active.
module dpram_scratch (
    input  wire        clk,
    input  wire        rst_n,
    input  wire        dma_active,

    // Port A: CPU read/write, or DMA write
    input  wire        cpu_en,
    input  wire        cpu_we,
    input  wire [12:0] cpu_addr,
    input  wire [31:0] cpu_wdata,
    output wire [31:0] cpu_rdata,
    output reg         cpu_rvalid,

    input  wire        dma_we,
    input  wire [12:0] dma_addr,
    input  wire [31:0] dma_wdata,

    // Port B: DMA read
    input  wire        dma_rd_en,
    input  wire [12:0] dma_rd_addr,
    output wire [31:0] dma_rd_data,
    output reg         dma_rd_valid
);

    (* ram_style = "block" *) reg [31:0] mem [0:8191];

    wire        port_a_we   = dma_active ? dma_we : (cpu_en && cpu_we);
    wire [12:0] port_a_addr = dma_active ? dma_addr : cpu_addr;
    wire [31:0] port_a_din  = dma_active ? dma_wdata : cpu_wdata;

    reg [31:0] dout_a;
    reg [31:0] dout_b;

    // Standard true-dual-port template: one write/read port A, one read port B.
    always @(posedge clk) begin
        if (port_a_we)
            mem[port_a_addr] <= port_a_din;
        dout_a <= mem[port_a_addr];
        dout_b <= mem[dma_rd_addr];
    end

    always @(posedge clk or negedge rst_n) begin
        if (!rst_n) begin
            cpu_rvalid   <= 1'b0;
            dma_rd_valid <= 1'b0;
        end else begin
            cpu_rvalid   <= cpu_en && !dma_active;
            dma_rd_valid <= dma_rd_en;
        end
    end

    assign cpu_rdata   = dout_a;
    assign dma_rd_data = dout_b;

endmodule
