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

`default_nettype none

{# Ensure board_config is always defined with fallbacks #}
{% if not board_config is defined %}
{% set board_config = {} %}
{% endif %}

// 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_type }}",
    parameter DEVICE_CLASS = "{{ device_class }}",
    parameter MAX_PAYLOAD_SIZE = {{ device_config.max_payload_size }},
    parameter MSI_VECTORS = {{ device_config.msi_vectors }},
    parameter COUNTER_WIDTH = {{ perf_config.counter_width if perf_config else 32 }}
) (
    // Clock and reset
    input wire  clk,
    input wire  reset_n,

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

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

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

    // Interrupt interface
    output logic msi_request,
    input wire  msi_ack,
    output logic [7:0] msi_vector,
    input wire  cfg_interrupt_msi_enable,
    output logic cfg_interrupt,
    input wire  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
{%- if device_specific_ports is defined %}
{%- include 'sv/components/device_specific_ports.sv.j2' %}
{%- endif %}
);

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

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

{%- if clock_domain_logic is defined %}
{%- include 'sv/components/clock_domain_logic.sv.j2' %}
{%- endif %}

{%- if interrupt_logic is defined %}
{%- include 'sv/components/interrupt_logic.sv.j2' %}
{%- endif %}

{%- if register_logic is defined %}
{%- include 'sv/components/register_logic.sv.j2' %}
{%- endif %}

{%- if read_logic is defined %}
{%- include 'sv/components/read_logic.sv.j2' %}
{%- endif %}

endmodule

`default_nettype wire