{#- Sampling Logic Template -#}
{#- Generates performance sampling logic -#}
{{ header | safe }}

module sampling_logic #(
    parameter COUNTER_WIDTH = {{ config.counter_width | default(32) }},
    parameter NUM_METRICS = {{ config.metrics_to_monitor|length | default(4) }},
    parameter SAMPLING_PERIOD = {{ config.sampling_period | default(1000) }}
) (
    input  logic clk,
    input  logic rst_n,
    
    // Metric inputs
    input  logic [COUNTER_WIDTH-1:0] transaction_count,
    input  logic [COUNTER_WIDTH-1:0] latency_accumulator,
    input  logic [COUNTER_WIDTH-1:0] bandwidth_counter,
    input  logic [COUNTER_WIDTH-1:0] error_count,
    input  logic [COUNTER_WIDTH-1:0] performance_data,
    
    // Sample outputs
    output logic sample_trigger,
    output logic [COUNTER_WIDTH-1:0] sample_data [NUM_METRICS-1:0]
);

// Performance Sampling Logic
logic [COUNTER_WIDTH-1:0] sample_counter;
logic sample_valid;

// Sample counter for periodic sampling
always_ff @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin
        sample_counter <= COUNTER_WIDTH'h0;
        sample_valid <= 1'b0;
    end else begin
        if (sample_counter >= SAMPLING_PERIOD) begin
            sample_counter <= COUNTER_WIDTH'h0;
            sample_valid <= 1'b1;
        end else begin
            sample_counter <= sample_counter + 1'b1;
            sample_valid <= 1'b0;
        end
    end
end

// Sample data capture
always_ff @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin
        {% for i in range(config.metrics_to_monitor|length) -%}
        sample_data[{{ i }}] <= COUNTER_WIDTH'h0;
        {% endfor %}
    end else if (sample_valid) begin
        {% for metric in config.metrics_to_monitor -%}
        {% if metric.value == "tlp_count" -%}
        sample_data[{{ loop.index0 }}] <= transaction_count;
        {% elif metric.value == "completion_latency" -%}
        sample_data[{{ loop.index0 }}] <= latency_accumulator;
        {% elif metric.value == "bandwidth_utilization" -%}
        sample_data[{{ loop.index0 }}] <= bandwidth_counter;
        {% elif metric.value == "error_rate" -%}
        sample_data[{{ loop.index0 }}] <= error_count;
        {% else -%}
        sample_data[{{ loop.index0 }}] <= performance_data;
        {% endif %}
        {% endfor %}
    end
end

// Sample trigger output
assign sample_trigger = sample_valid;

endmodule
