{#- Sampling Logic Template -#}
{{ header | safe }}

module sampling_logic #(
    parameter COUNTER_WIDTH = {{ config.counter_width }},
    {%- set metrics = config.metrics_to_monitor | default([]) %}
    parameter NUM_METRICS = {{ (metrics|length) if metrics else 1 }},
    parameter SAMPLING_PERIOD = {{ config.sampling_period }}
) (
    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;
        sample_trigger <= 1'b0;
    end else begin
        if (sample_counter >= SAMPLING_PERIOD) begin
            sample_counter <= COUNTER_WIDTH'h0;
            sample_valid <= 1'b1;
            sample_trigger <= 1'b1;
        end else begin
            sample_counter <= sample_counter + 1'b1;
            sample_valid <= 1'b0;
            sample_trigger <= 1'b0;
        end
    end
end

// Sample data capture
always_ff @(posedge clk or negedge rst_n) begin
    if (!rst_n) begin
    {%- if metrics -%}
    {%- for i in range(metrics|length) -%}
    sample_data[{{ i }}] <= COUNTER_WIDTH'h0;
    {%- endfor -%}
    {%- else -%}
    sample_data[0] <= COUNTER_WIDTH'h0;
    {%- endif -%}
    end else if (sample_valid) begin
    {%- if metrics -%}
    {% for metric in metrics -%}
    {% set metric_value = metric.value if metric is defined and metric.value is defined else (metric.get('value', metric.get('name', 'tlp_count')) if metric is mapping else metric) -%}
    {% 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 %}
    {%- else -%}
    // No metrics configured - provide single placeholder mapping
    sample_data[0] <= performance_data;
    {%- endif -%}
    end
end

endmodule
