{#- Advanced PCIe Device Controller Template -#}
{{ header | safe }}

// State machine definitions
`define S_SHADOW_CFGSPACE_IDLE  2'b00
`define S_SHADOW_CFGSPACE_TLP   2'b01
`define S_SHADOW_CFGSPACE_USB   2'b10

module advanced_pcileech_controller #(
    parameter DEVICE_TYPE = "{{ device_config.device_type.value }}",
    parameter DEVICE_CLASS = "{{ device_config.device_class.value }}",
    parameter MAX_PAYLOAD_SIZE = {{ device_config.max_payload_size }},
    parameter MSI_VECTORS = {{ device_config.msi_vectors }},
    parameter COUNTER_WIDTH = {{ perf_config.counter_width_bits if perf_config else 32 }}
) (
    // Clock and reset
    input logic clk,
    input logic reset_n,

    // Additional clock domains
    input logic mem_clk,
    input logic aux_clk,

    // PCIe interface
    input logic [31:0] bar_addr,
    input logic [31:0] bar_wr_data,
    input logic bar_wr_en,
    input logic bar_rd_en,
    output logic [31:0] bar_rd_data,

    // Power management interface
    input logic [1:0] power_state_req,
    output logic [1:0] power_state_ack,
    input logic [1:0] link_state_req,
    output logic [1:0] link_state_ack,

    // Interrupt interface
    output logic msi_request,
    input logic msi_ack,
    output logic [7:0] msi_vector,
    input logic cfg_interrupt_msi_enable,
    output logic cfg_interrupt,
    input logic cfg_interrupt_ready,

    // Error reporting interface
    output logic correctable_error,
    output logic uncorrectable_error,
    output logic [7:0] error_code,

    // Performance monitoring interface
    output logic [COUNTER_WIDTH-1:0] perf_counter_0,
    output logic [COUNTER_WIDTH-1:0] perf_counter_1,
    output logic [COUNTER_WIDTH-1:0] perf_counter_2,
    output logic [COUNTER_WIDTH-1:0] perf_counter_3,

    // Device-specific interfaces
{%- include 'systemverilog/components/device_specific_ports.sv.j2' %}
);

{%- if power_config %}
{%- include 'systemverilog/advanced/power_management.sv.j2' %}
{%- endif %}

{%- if error_config %}
{%- include 'systemverilog/advanced/error_handling.sv.j2' %}
{%- endif %}

{%- if perf_config %}
{%- include 'systemverilog/advanced/performance_counters.sv.j2' %}
{%- endif %}

{%- include 'systemverilog/components/clock_domain_logic.sv.j2' %}

{%- include 'systemverilog/components/interrupt_logic.sv.j2' %}

{%- include 'systemverilog/components/register_logic.sv.j2' %}

{%- include 'systemverilog/components/read_logic.sv.j2' %}

endmodule