//==============================================================================
// TLP 128-bit BAR Controller Top Level - Integration Shell
// Generated by PCILeech Firmware Generator
//
// This module serves as the top-level integration shell that replaces the
// original monolithic pcileech_tlps128_bar_controller.sv module:
// - Thin wiring shell connecting all refactored sub-modules
// - Parameter propagation and configuration management
// - Clock and reset distribution
// - Interface compatibility with existing PCIe infrastructure
// - Behavioral equivalence with original monolithic design
// - The future implementation sections just mean later on in the build 
//   they'll get the values
//==============================================================================

`include "../tlp_pkg.svh"
`include "../bar_layout_pkg.svh"

module tlps128_bar_top
    import tlp_pkg::*;
    import bar_layout_pkg::*;
#(
    // Configuration parameters (replaces Jinja2 placeholders)
    parameter bar_config_t BAR_CONFIG = DEFAULT_BAR_CONFIG,
    parameter msix_config_t MSIX_CONFIG = DEFAULT_MSIX_CONFIG,
    parameter timing_config_t TIMING_CONFIG = DEFAULT_TIMING_CONFIG,
    parameter device_config_t DEVICE_CONFIG = DEFAULT_DEVICE_CONFIG,
    
    // Feature enables
    parameter bit ENABLE_DUAL_PORT_BUFFER = 1'b1,
    parameter bit ENABLE_BURST_OPTIMIZATION = 1'b1,
    parameter bit ENABLE_MANUFACTURING_VARIANCE = 1'b0,
    parameter bit ENABLE_ACCESS_LOGGING = 1'b1,
    parameter bit ENABLE_RANGE_CHECKING = 1'b1
) (
    // Clock and Reset
    input  logic                clk,
    input  logic                reset_n,
    
    // PCIe TLP 128-bit Interface (identical to original)
    input  logic                tlp_rx_valid,
    input  logic [127:0]        tlp_rx_data,
    input  logic                tlp_rx_sop,
    input  logic                tlp_rx_eop,
    input  logic [3:0]          tlp_rx_empty,
    input  logic                tlp_rx_err,
    output logic                tlp_rx_ready,
    
    output logic                tlp_tx_valid,
    output logic [127:0]        tlp_tx_data,
    output logic                tlp_tx_sop,
    output logic                tlp_tx_eop,
    output logic [3:0]          tlp_tx_empty,
    input  logic                tlp_tx_ready,
    output logic                tlp_tx_err,
    
    // BAR Access Interface (identical to original)
    input  logic [31:0]         bar_addr,
    input  logic [31:0]         bar_wr_data,
    input  logic [3:0]          bar_wr_be,
    input  logic                bar_wr_en,
    input  logic                bar_rd_en,
    output logic [31:0]         bar_rd_data,
    output logic                bar_rd_valid,
    
    // Configuration Space Interface (identical to original)
    input  logic                cfg_ext_read_received,
    input  logic                cfg_ext_write_received,
    input  logic [9:0]          cfg_ext_register_number,
    input  logic [3:0]          cfg_ext_function_number,
    input  logic [31:0]         cfg_ext_write_data,
    input  logic [3:0]          cfg_ext_write_byte_enable,
    output logic [31:0]         cfg_ext_read_data,
    output logic                cfg_ext_read_data_valid,
    
    // MSI-X Interrupt Interface (identical to original)
    output logic                msix_interrupt,
    output logic [10:0]         msix_vector,
    input  logic                msix_interrupt_ack,
    
    // PCILeech Control Interface (identical to original)
    input  logic                pcileech_enable,
    input  logic [31:0]         pcileech_command,
    input  logic [63:0]         pcileech_address,
    input  logic [31:0]         pcileech_length,
    output logic [31:0]         pcileech_status,
    output logic                pcileech_ready,
    
    // DMA Interface (identical to original)
    output logic                dma_read_req,
    output logic [63:0]         dma_read_addr,
    output logic [31:0]         dma_read_len,
    input  logic                dma_read_ack,
    input  logic [127:0]        dma_read_data,
    input  logic                dma_read_valid,
    
    output logic                dma_write_req,
    output logic [63:0]         dma_write_addr,
    output logic [31:0]         dma_write_len,
    output logic [127:0]        dma_write_data,
    input  logic                dma_write_ack,
    
    // Status and Debug (identical to original)
    output logic [31:0]         error_status,
    output logic [31:0]         performance_counter_0,
    output logic [31:0]         performance_counter_1,
    output logic [7:0]          debug_state
);

    // ========================================================================
    // Internal Signal Declarations
    // ========================================================================
    
    // TLP Frontend to BAR Dispatcher
    logic                       parsed_tlp_valid;
    tlp_header_t                parsed_tlp_header;
    logic [63:0]                parsed_tlp_address;
    logic [127:0]               parsed_tlp_data;
    logic                       parsed_tlp_has_data;
    logic [11:0]                parsed_tlp_byte_count;
    logic                       parsed_tlp_error;
    logic                       parsed_tlp_ready;
    
    // BAR Dispatcher to Region Modules
    // Device Control Region
    logic                       device_ctrl_req_valid;
    logic [31:0]                device_ctrl_req_addr;
    logic [31:0]                device_ctrl_req_data;
    logic [3:0]                 device_ctrl_req_be;
    logic                       device_ctrl_req_write;
    tlp_header_t                device_ctrl_req_header;
    logic                       device_ctrl_req_ready;
    logic                       device_ctrl_resp_valid;
    logic [31:0]                device_ctrl_resp_data;
    logic                       device_ctrl_resp_error;
    logic                       device_ctrl_resp_ready;
    
    // Status Region
    logic                       status_reg_req_valid;
    logic [31:0]                status_reg_req_addr;
    logic [31:0]                status_reg_req_data;
    logic [3:0]                 status_reg_req_be;
    logic                       status_reg_req_write;
    tlp_header_t                status_reg_req_header;
    logic                       status_reg_req_ready;
    logic                       status_reg_resp_valid;
    logic [31:0]                status_reg_resp_data;
    logic                       status_reg_resp_error;
    logic                       status_reg_resp_ready;
    
    // Data Buffer Region
    logic                       data_buffer_req_valid;
    logic [31:0]                data_buffer_req_addr;
    logic [31:0]                data_buffer_req_data;
    logic [3:0]                 data_buffer_req_be;
    logic                       data_buffer_req_write;
    tlp_header_t                data_buffer_req_header;
    logic                       data_buffer_req_ready;
    logic                       data_buffer_resp_valid;
    logic [31:0]                data_buffer_resp_data;
    logic                       data_buffer_resp_error;
    logic                       data_buffer_resp_ready;
    
    // Custom PIO Region (implementated later in build)
    logic                       custom_pio_req_valid;
    logic [31:0]                custom_pio_req_addr;
    logic [31:0]                custom_pio_req_data;
    logic [3:0]                 custom_pio_req_be;
    logic                       custom_pio_req_write;
    tlp_header_t                custom_pio_req_header;
    logic                       custom_pio_req_ready;
    logic                       custom_pio_resp_valid;
    logic [31:0]                custom_pio_resp_data;
    logic                       custom_pio_resp_error;
    logic                       custom_pio_resp_ready;
    
    // MSI-X Engine (implementated later in build)
    logic                       msix_req_valid;
    logic [31:0]                msix_req_addr;
    logic [31:0]                msix_req_data;
    logic [3:0]                 msix_req_be;
    logic                       msix_req_write;
    tlp_header_t                msix_req_header;
    logic                       msix_req_ready;
    logic                       msix_resp_valid;
    logic [31:0]                msix_resp_data;
    logic                       msix_resp_error;
    logic                       msix_resp_ready;
    
    // Completion Interface
    logic                       completion_valid;
    tlp_completion_header_t     completion_header;
    logic [127:0]               completion_data;
    logic                       completion_has_data;
    logic                       completion_ready;
    
    // Control and Status Interconnect
    logic                       pcileech_enable_int;
    logic [31:0]                pcileech_control_int;
    logic [31:0]                device_capabilities;
    logic [31:0]                device_status_int;
    
    // Performance and Error Monitoring
    performance_counters_t      perf_counters;
    error_status_t              error_status_int;
    logic [31:0]                uptime_seconds;
    logic [31:0]                total_transactions;
    
    // Buffer management
    logic [31:0]                buffer_fill_level;
    logic                       buffer_full;
    logic                       buffer_empty;
    logic                       buffer_overflow;
    logic                       buffer_underflow;
    
    // Debug and monitoring
    logic [31:0]                access_count;
    logic [31:0]                dispatcher_error_count;
    region_select_t             current_region;
    logic [31:0]                current_address;
    
    // ========================================================================
    // Active Device Interrupt Signals
    // ========================================================================
    
    // Interrupt sources and control
    localparam int NUM_INTERRUPT_SOURCES = 8;
    logic [NUM_INTERRUPT_SOURCES-1:0] interrupt_sources;
    logic [3:0]                 source_priority[NUM_INTERRUPT_SOURCES];
    logic [NUM_INTERRUPT_SOURCES-1:0] interrupt_ack;
    
    // Configuration space interface signals for MSI
    logic                       cfg_interrupt;
    logic                       cfg_interrupt_assert;
    logic                       cfg_interrupt_di;
    logic                       cfg_interrupt_rdy;
    logic                       cfg_interrupt_mmenable;
    logic                       cfg_interrupt_msienable;
    logic                       cfg_interrupt_msixenable;
    logic                       cfg_interrupt_msixfm;
    logic [7:0]                 cfg_interrupt_do;
    logic [7:0]                 cfg_interrupt_di_in;
    logic                       cfg_interrupt_stat;
    logic [4:0]                 cfg_pciecap_interrupt_msgnum;
    
    // TLP interface for MSI-X from interrupt controller
    logic                       msix_tlp_tx_valid;
    logic [127:0]               msix_tlp_tx_data;
    logic                       msix_tlp_tx_sop;
    logic                       msix_tlp_tx_eop;
    logic [3:0]                 msix_tlp_tx_empty;
    logic                       msix_tlp_tx_ready;
    
    // Control and status for interrupt controller
    logic                       interrupt_enable;
    logic [31:0]                timer_reload_value;
    logic                       timer_interrupt_pending;
    logic [31:0]                interrupt_count;
    logic [31:0]                interrupt_status;
    logic [7:0]                 current_vector;
    logic [3:0]                 interrupt_debug_state;

    // ========================================================================
    // Command Register Bit Extraction
    // ========================================================================
    
    // Extract command register bits from pcileech_command input
    logic cfg_bus_master_enable_dynamic;
    logic cfg_memory_space_enable_dynamic;
    logic cfg_interrupt_disable_dynamic;
    
    always_comb begin
        // Extract individual bits from pcileech_command (PCI command register format)
        cfg_bus_master_enable_dynamic = pcileech_command[2];     // Bit 2: Bus Master Enable
        cfg_memory_space_enable_dynamic = pcileech_command[1];   // Bit 1: Memory Space Enable
        cfg_interrupt_disable_dynamic = pcileech_command[10];    // Bit 10: Interrupt Disable
    end
    
    tlp_frontend #(
        .COMPLETER_ID(16'h0000),  // Should be parameterized from device config
        .ENABLE_ERROR_CHECKING(1'b1),
        .TIMEOUT_CYCLES(TIMING_CONFIG.timeout_cycles)
    ) u_tlp_frontend (
        .clk(clk),
        .reset_n(reset_n),
        
        // TLP Input Interface
        .tlp_rx_valid(tlp_rx_valid),
        .tlp_rx_data(tlp_rx_data),
        .tlp_rx_sop(tlp_rx_sop),
        .tlp_rx_eop(tlp_rx_eop),
        .tlp_rx_empty(tlp_rx_empty),
        .tlp_rx_err(tlp_rx_err),
        .tlp_rx_ready(tlp_rx_ready),
        
        // Parsed TLP Output Interface
        .parsed_tlp_valid(parsed_tlp_valid),
        .parsed_tlp_header(parsed_tlp_header),
        .parsed_tlp_address(parsed_tlp_address),
        .parsed_tlp_data(parsed_tlp_data),
        .parsed_tlp_has_data(parsed_tlp_has_data),
        .parsed_tlp_byte_count(parsed_tlp_byte_count),
        .parsed_tlp_ready(parsed_tlp_ready),
        
        // Error and Status Outputs
        .tlp_parse_error(parsed_tlp_error),
        .tlp_error_code(),  // Not used in this integration
        .tlp_parse_count(),
        .tlp_error_count()
    );

    // ========================================================================
    // BAR Dispatcher Module
    // ========================================================================
    
    bar_dispatcher #(
        .ENABLE_ACCESS_LOGGING(ENABLE_ACCESS_LOGGING),
        .ENABLE_RANGE_CHECKING(ENABLE_RANGE_CHECKING)
    ) u_bar_dispatcher (
        .clk(clk),
        .reset_n(reset_n),
        
        // Input from TLP Frontend
        .parsed_tlp_valid(parsed_tlp_valid),
        .parsed_tlp_header(parsed_tlp_header),
        .parsed_tlp_address(parsed_tlp_address),
        .parsed_tlp_data(parsed_tlp_data),
        .parsed_tlp_has_data(parsed_tlp_has_data),
        .parsed_tlp_byte_count(parsed_tlp_byte_count),
        .parsed_tlp_error(parsed_tlp_error),
        .parsed_tlp_ready(parsed_tlp_ready),
        
        // Region Interfaces
        .device_ctrl_req_valid(device_ctrl_req_valid),
        .device_ctrl_req_addr(device_ctrl_req_addr),
        .device_ctrl_req_data(device_ctrl_req_data),
        .device_ctrl_req_be(device_ctrl_req_be),
        .device_ctrl_req_write(device_ctrl_req_write),
        .device_ctrl_req_header(device_ctrl_req_header),
        .device_ctrl_req_ready(device_ctrl_req_ready),
        .device_ctrl_resp_valid(device_ctrl_resp_valid),
        .device_ctrl_resp_data(device_ctrl_resp_data),
        .device_ctrl_resp_error(device_ctrl_resp_error),
        .device_ctrl_resp_ready(device_ctrl_resp_ready),
        
        .status_reg_req_valid(status_reg_req_valid),
        .status_reg_req_addr(status_reg_req_addr),
        .status_reg_req_data(status_reg_req_data),
        .status_reg_req_be(status_reg_req_be),
        .status_reg_req_write(status_reg_req_write),
        .status_reg_req_header(status_reg_req_header),
        .status_reg_req_ready(status_reg_req_ready),
        .status_reg_resp_valid(status_reg_resp_valid),
        .status_reg_resp_data(status_reg_resp_data),
        .status_reg_resp_error(status_reg_resp_error),
        .status_reg_resp_ready(status_reg_resp_ready),
        
        .data_buffer_req_valid(data_buffer_req_valid),
        .data_buffer_req_addr(data_buffer_req_addr),
        .data_buffer_req_data(data_buffer_req_data),
        .data_buffer_req_be(data_buffer_req_be),
        .data_buffer_req_write(data_buffer_req_write),
        .data_buffer_req_header(data_buffer_req_header),
        .data_buffer_req_ready(data_buffer_req_ready),
        .data_buffer_resp_valid(data_buffer_resp_valid),
        .data_buffer_resp_data(data_buffer_resp_data),
        .data_buffer_resp_error(data_buffer_resp_error),
        .data_buffer_resp_ready(data_buffer_resp_ready),
        
        .custom_pio_req_valid(custom_pio_req_valid),
        .custom_pio_req_addr(custom_pio_req_addr),
        .custom_pio_req_data(custom_pio_req_data),
        .custom_pio_req_be(custom_pio_req_be),
        .custom_pio_req_write(custom_pio_req_write),
        .custom_pio_req_header(custom_pio_req_header),
        .custom_pio_req_ready(custom_pio_req_ready),
        .custom_pio_resp_valid(custom_pio_resp_valid),
        .custom_pio_resp_data(custom_pio_resp_data),
        .custom_pio_resp_error(custom_pio_resp_error),
        .custom_pio_resp_ready(custom_pio_resp_ready),
        
        .msix_req_valid(msix_req_valid),
        .msix_req_addr(msix_req_addr),
        .msix_req_data(msix_req_data),
        .msix_req_be(msix_req_be),
        .msix_req_write(msix_req_write),
        .msix_req_header(msix_req_header),
        .msix_req_ready(msix_req_ready),
        .msix_resp_valid(msix_resp_valid),
        .msix_resp_data(msix_resp_data),
        .msix_resp_error(msix_resp_error),
        .msix_resp_ready(msix_resp_ready),
        
        // Completion Output Interface
        .completion_valid(completion_valid),
        .completion_header(completion_header),
        .completion_data(completion_data),
        .completion_has_data(completion_has_data),
        .completion_ready(completion_ready),
        
        // Status and Debug
        .access_count(access_count),
        .error_count(dispatcher_error_count),
        .current_region(current_region),
        .current_address(current_address)
    );

    // ========================================================================
    // Device Control Region Module
    // ========================================================================
    
    region_device_ctrl #(
        .DEVICE_CONFIG(DEVICE_CONFIG),
        .ENABLE_MANUFACTURING_VARIANCE(ENABLE_MANUFACTURING_VARIANCE)
    ) u_region_device_ctrl (
        .clk(clk),
        .reset_n(reset_n),
        
        // Request Interface
        .req_valid(device_ctrl_req_valid),
        .req_addr(device_ctrl_req_addr),
        .req_data(device_ctrl_req_data),
        .req_be(device_ctrl_req_be),
        .req_write(device_ctrl_req_write),
        .req_header(device_ctrl_req_header),
        .req_ready(device_ctrl_req_ready),
        
        // Response Interface
        .resp_valid(device_ctrl_resp_valid),
        .resp_data(device_ctrl_resp_data),
        .resp_error(device_ctrl_resp_error),
        .resp_ready(device_ctrl_resp_ready),
        
        // Control Outputs
        .pcileech_enable(pcileech_enable_int),
        .pcileech_control(pcileech_control_int),
        .device_capabilities(device_capabilities),
        .device_status(device_status_int),
        
        // Configuration Interface
        .cfg_bus_master_enable(cfg_bus_master_enable_dynamic),  // Dynamic from pcileech_command
        .cfg_memory_space_enable(cfg_memory_space_enable_dynamic),
        .cfg_interrupt_disable(cfg_interrupt_disable_dynamic),
        
        // Status Inputs
        .error_status(error_status_int),
        .performance_counter_0(perf_counters.read_count),
        .performance_counter_1(perf_counters.write_count),
        
        // Debug outputs (not connected in this integration)
        .debug_register_access(),
        .last_write_data(),
        .last_write_addr()
    );

    // ========================================================================
    // Status Register Region Module
    // ========================================================================
    
    region_status #(
        .DEVICE_CONFIG(DEVICE_CONFIG),
        .ENABLE_PERFORMANCE_COUNTERS(DEVICE_CONFIG.enable_perf_counters),
        .ENABLE_ERROR_LOGGING(1'b1)
    ) u_region_status (
        .clk(clk),
        .reset_n(reset_n),
        
        // Request Interface
        .req_valid(status_reg_req_valid),
        .req_addr(status_reg_req_addr),
        .req_data(status_reg_req_data),
        .req_be(status_reg_req_be),
        .req_write(status_reg_req_write),
        .req_header(status_reg_req_header),
        .req_ready(status_reg_req_ready),
        
        // Response Interface
        .resp_valid(status_reg_resp_valid),
        .resp_data(status_reg_resp_data),
        .resp_error(status_reg_resp_error),
        .resp_ready(status_reg_resp_ready),
        
        // Performance Counter Inputs
        .perf_read_increment(device_ctrl_req_valid && !device_ctrl_req_write),
        .perf_write_increment(device_ctrl_req_valid && device_ctrl_req_write),
        .perf_completion_increment(completion_valid),
        .perf_error_increment(parsed_tlp_error),
        .perf_latency_sample(16'h0010),  // Placeholder
        .perf_latency_valid(1'b0),
        
        // Error Status Inputs
        .error_address_fault(1'b0),  // Connected to actual error sources
        .error_tlp_malformed(parsed_tlp_error),
        .error_timeout(1'b0),
        .error_parity(1'b0),
        .error_completion(1'b0),
        .error_unsupported(1'b0),
        .error_dma_fault(1'b0),
        
        // Control Inputs
        .ctrl_reset_counters(1'b0),  // Connected to control register
        .ctrl_reset_errors(1'b0),
        .ctrl_enable_logging(1'b1),
        
        // Status Outputs
        .perf_counters(perf_counters),
        .error_status(error_status_int),
        .uptime_seconds(uptime_seconds),
        .total_transactions(total_transactions)
    );

    // ========================================================================
    // Data Buffer Region Module
    // ========================================================================
    
    region_data_buffer #(
        .ENABLE_DUAL_PORT(ENABLE_DUAL_PORT_BUFFER),
        .ENABLE_BURST_OPTIMIZATION(ENABLE_BURST_OPTIMIZATION),
        .BURST_SIZE(16)
    ) u_region_data_buffer (
        .clk(clk),
        .reset_n(reset_n),
        
        // Request Interface
        .req_valid(data_buffer_req_valid),
        .req_addr(data_buffer_req_addr),
        .req_data(data_buffer_req_data),
        .req_be(data_buffer_req_be),
        .req_write(data_buffer_req_write),
        .req_header(data_buffer_req_header),
        .req_ready(data_buffer_req_ready),
        
        // Response Interface
        .resp_valid(data_buffer_resp_valid),
        .resp_data(data_buffer_resp_data),
        .resp_error(data_buffer_resp_error),
        .resp_ready(data_buffer_resp_ready),
        
        // DMA Interface (not connected in this integration)
        .dma_buffer_req(1'b0),
        .dma_buffer_addr(32'h0),
        .dma_buffer_wdata(32'h0),
        .dma_buffer_be(4'h0),
        .dma_buffer_write(1'b0),
        .dma_buffer_rdata(),
        .dma_buffer_ready(),
        .dma_buffer_valid(),
        
        // Buffer Status and Control
        .buffer_flush(1'b0),
        .buffer_clear(1'b0),
        .buffer_fill_level(buffer_fill_level),
        .buffer_full(buffer_full),
        .buffer_empty(buffer_empty),
        .buffer_overflow(buffer_overflow),
        .buffer_underflow(buffer_underflow),
        
        // Performance and Debug
        .buffer_read_count(),
        .buffer_write_count(),
        .buffer_burst_count(),
        .buffer_state()
    );

    // ========================================================================
    // Placeholder Module
    // ========================================================================    
    // Custom PIO Region
    always_comb begin
        // Always ready to accept new requests
        custom_pio_req_ready = 1'b1;
        
        // Valid response when request is valid
        custom_pio_resp_valid = custom_pio_req_valid;
        
        // Return address-based data for read operations
        if (custom_pio_req_valid && !custom_pio_req_write) begin
            case (custom_pio_req_addr[7:2])  // Word-aligned addressing
                6'h00: custom_pio_resp_data = 32'h00010020;  // Device ID and version
                6'h01: custom_pio_resp_data = 32'h00000100;  // Status register
                6'h02: custom_pio_resp_data = 32'h00000000;  // Control register
                6'h03: custom_pio_resp_data = 32'h00000000;  // Reserved
                6'h04: custom_pio_resp_data = 32'h00000001;  // Capabilities
                6'h05: custom_pio_resp_data = 32'h00000000;  // Interrupt status
                6'h06: custom_pio_resp_data = 32'h00000000;  // Interrupt mask
                6'h07: custom_pio_resp_data = 32'h00000000;  // Error flags
                default: custom_pio_resp_data = 32'h00000000;  // Default value for unmapped registers
            endcase
        end else begin
            // Default response for write operations
            custom_pio_resp_data = 32'h00000000;
        end
        
        // No errors for now
        custom_pio_resp_error = 1'b0;
    end

    
    // ========================================================================
    // Active Device Interrupt Controller
    // ========================================================================
    
    // Initialize interrupt sources (example mapping)
    always_comb begin
        interrupt_sources = '0;
        interrupt_sources[0] = buffer_overflow;      // Buffer overflow interrupt
        interrupt_sources[1] = buffer_underflow;     // Buffer underflow interrupt
        interrupt_sources[2] = parsed_tlp_error;     // TLP parse error interrupt
        // Other sources can be added as needed
        
        // Set interrupt priorities
        for (int i = 0; i < NUM_INTERRUPT_SOURCES; i++) begin
            source_priority[i] = 4'h5;  // Default medium priority
        end
        source_priority[0] = 4'h8;  // Higher priority for buffer overflow
        source_priority[1] = 4'h8;  // Higher priority for buffer underflow
        source_priority[2] = 4'h7;  // High priority for TLP errors
    end
    
    // Control signals
    assign interrupt_enable = pcileech_enable_int;
    assign timer_reload_value = 32'h0001_0000;  // Default timer period
    
    // Configuration interface signals (simplified for now)
    assign cfg_interrupt_rdy = 1'b1;
    assign cfg_interrupt_mmenable = 3'b000;
    assign cfg_interrupt_msienable = 1'b0;
    assign cfg_interrupt_msixenable = 1'b1;  // Enable MSI-X by default
    assign cfg_interrupt_msixfm = 1'b0;      // Function not masked
    assign cfg_interrupt_di_in = 8'h00;
    
    active_device_interrupt #(
        .TIMER_PERIOD(32'h0010_0000),           // ~1M cycles between timer interrupts
        .TIMER_ENABLE(1'b1),                    // Enable periodic timer
        .MSI_VECTOR_WIDTH(5),                   // 32 MSI vectors
        .MSI_64BIT_ADDR(1'b0),                  // 32-bit MSI addresses
        .NUM_MSIX(MSIX_CONFIG.num_vectors),     // From configuration
        .MSIX_TABLE_BIR(MSIX_CONFIG.table_bir),
        .MSIX_TABLE_OFFSET(MSIX_CONFIG.table_offset),
        .MSIX_PBA_BIR(MSIX_CONFIG.pba_bir),
        .MSIX_PBA_OFFSET(MSIX_CONFIG.pba_offset),
        .DEVICE_ID(DEVICE_CONFIG.device_id),
        .VENDOR_ID(DEVICE_CONFIG.vendor_id),
        .COMPLETER_ID(16'h0000),                // Should be from config
        .NUM_INTERRUPT_SOURCES(NUM_INTERRUPT_SOURCES),
        .DEFAULT_PRIORITY(4'h5)
    ) u_active_device_interrupt (
        // Clock and Reset
        .clk(clk),
        .reset_n(reset_n),
        
        // Interrupt Source Interface
        .interrupt_sources(interrupt_sources),
        .source_priority(source_priority),
        .interrupt_ack(interrupt_ack),
        
        // Configuration Space Interface (for MSI)
        .cfg_interrupt(cfg_interrupt),
        .cfg_interrupt_assert(cfg_interrupt_assert),
        .cfg_interrupt_di(cfg_interrupt_di),
        .cfg_interrupt_rdy(cfg_interrupt_rdy),
        .cfg_interrupt_mmenable(cfg_interrupt_mmenable),
        .cfg_interrupt_msienable(cfg_interrupt_msienable),
        .cfg_interrupt_msixenable(cfg_interrupt_msixenable),
        .cfg_interrupt_msixfm(cfg_interrupt_msixfm),
        .cfg_interrupt_do(cfg_interrupt_do),
        .cfg_interrupt_di_in(cfg_interrupt_di_in),
        .cfg_interrupt_stat(cfg_interrupt_stat),
        .cfg_pciecap_interrupt_msgnum(cfg_pciecap_interrupt_msgnum),
        
        // TLP Interface (for MSI-X)
        .tlp_tx_valid(msix_tlp_tx_valid),
        .tlp_tx_data(msix_tlp_tx_data),
        .tlp_tx_sop(msix_tlp_tx_sop),
        .tlp_tx_eop(msix_tlp_tx_eop),
        .tlp_tx_empty(msix_tlp_tx_empty),
        .tlp_tx_ready(msix_tlp_tx_ready),
        
        // MSI-X Table Interface
        .msix_table_addr(msix_req_addr),
        .msix_table_wr_en(msix_req_write && msix_req_valid),
        .msix_table_wr_data(msix_req_data),
        .msix_table_wr_be(msix_req_be),
        .msix_table_rd_en(!msix_req_write && msix_req_valid),
        .msix_table_rd_data(msix_resp_data),
        
        // Control and Status
        .interrupt_enable(interrupt_enable),
        .timer_reload_value(timer_reload_value),
        .timer_interrupt_pending(timer_interrupt_pending),
        .interrupt_count(interrupt_count),
        .interrupt_status(interrupt_status),
        .current_vector(current_vector),
        .debug_state(interrupt_debug_state)
    );
    
    // MSI-X table access response
    always_ff @(posedge clk) begin
        if (!reset_n) begin
            msix_resp_valid <= 1'b0;
            msix_resp_error <= 1'b0;
        end else begin
            msix_resp_valid <= msix_req_valid;
            msix_resp_error <= 1'b0;
        end
    end
    
    assign msix_req_ready = 1'b1;  // Always ready for MSI-X table access
    
    // Map interrupt controller outputs to top-level MSI-X interface
    assign msix_interrupt = msix_tlp_tx_valid && msix_tlp_tx_sop;
    assign msix_vector = current_vector;

    // ========================================================================
    // TLP Completion and MSI-X Arbitration
    // ========================================================================
    
    // Simple arbitration between completion TLPs and MSI-X TLPs
    // Priority given to completions to avoid blocking memory transactions
    logic use_msix_tlp;
    
    always_comb begin
        if (completion_valid && !msix_tlp_tx_valid) begin
            // Only completion is valid
            use_msix_tlp = 1'b0;
            completion_ready = tlp_tx_ready;
            msix_tlp_tx_ready = 1'b0;
        end else if (!completion_valid && msix_tlp_tx_valid) begin
            // Only MSI-X is valid
            use_msix_tlp = 1'b1;
            completion_ready = 1'b0;
            msix_tlp_tx_ready = tlp_tx_ready;
        end else if (completion_valid && msix_tlp_tx_valid) begin
            // Both valid - prioritize completion
            use_msix_tlp = 1'b0;
            completion_ready = tlp_tx_ready;
            msix_tlp_tx_ready = 1'b0;
        end else begin
            // Neither valid
            use_msix_tlp = 1'b0;
            completion_ready = 1'b0;
            msix_tlp_tx_ready = 1'b0;
        end
    end
    
    // Multiplex TLP output
    always_comb begin
        if (use_msix_tlp) begin
            tlp_tx_valid = msix_tlp_tx_valid;
            tlp_tx_data = msix_tlp_tx_data;
            tlp_tx_sop = msix_tlp_tx_sop;
            tlp_tx_eop = msix_tlp_tx_eop;
            tlp_tx_empty = msix_tlp_tx_empty;
            tlp_tx_err = 1'b0;
        end else begin
            tlp_tx_valid = completion_valid;
            tlp_tx_sop = completion_valid;
            tlp_tx_eop = completion_valid;
            tlp_tx_empty = 4'h0;
            tlp_tx_err = 1'b0;
            
            // Pack completion header into TLP data
            tlp_tx_data = {completion_header, 32'h00000000};
            if (completion_has_data) begin
                tlp_tx_data[31:0] = completion_data[31:0];
            end
        end
    end

    // ========================================================================
    // Legacy Interface Compatibility
    // ========================================================================
    
    // BAR Access Interface (for backward compatibility)
    always_comb begin
        bar_rd_data = 32'h00000000;
        bar_rd_valid = 1'b0;
        
        // This interface is maintained for compatibility but not actively used
        // in the new architecture. All access goes through TLP interface.
    end
    
    // Configuration Space Interface
    always_comb begin
        cfg_ext_read_data = 32'h00000000;
        cfg_ext_read_data_valid = cfg_ext_read_received;
        
        // Basic configuration space responses
        if (cfg_ext_read_received) begin
            unique case (cfg_ext_register_number)
                10'h000: cfg_ext_read_data = {DEVICE_CONFIG.device_id, DEVICE_CONFIG.vendor_id};
                10'h001: cfg_ext_read_data = {16'h0010, pcileech_command[15:0]};  // Status/Command with dynamic command
                default: cfg_ext_read_data = 32'h00000000;
            endcase
        end
    end

    // ========================================================================
    // Output Assignments
    // ========================================================================
    
    // PCILeech Control Interface
    assign pcileech_status = {24'h000000, 8'h01};  // Ready status
    assign pcileech_ready = pcileech_enable_int;
    
    // DMA Interface (placeholder)
    assign dma_read_req = 1'b0;
    assign dma_read_addr = 64'h0;
    assign dma_read_len = 32'h0;
    assign dma_write_req = 1'b0;
    assign dma_write_addr = 64'h0;
    assign dma_write_len = 32'h0;
    assign dma_write_data = 128'h0;
    
    // Status and Debug
    assign error_status = error_status_int;
    assign performance_counter_0 = perf_counters.read_count;
    assign performance_counter_1 = perf_counters.write_count;
    assign debug_state = {5'b00000, current_region};

    // ========================================================================
    // Simulation Support
    // ========================================================================
    
`ifdef SIMULATION
    // Top-level monitoring
    always @(posedge clk) begin
        if (parsed_tlp_valid && parsed_tlp_ready) begin
            $display("[TLP BAR Top] TLP processed: type=%s, addr=0x%016X at time %0t",
                     parsed_tlp_header.fmt_type.name(),
                     parsed_tlp_address,
                     $time);
        end
        
        if (completion_valid && completion_ready) begin
            $display("[TLP BAR Top] Completion sent: status=%0d at time %0t",
                     completion_header.completion_status,
                     $time);
        end
        
        // Monitor command register bit changes
        static logic [31:0] prev_pcileech_command = 32'h0;
        if (pcileech_command != prev_pcileech_command) begin
            $display("[TLP BAR Top] Command register changed: 0x%08X -> 0x%08X at time %0t",
                     prev_pcileech_command, pcileech_command, $time);
            $display("[TLP BAR Top]   Bus Master: %b, Memory Space: %b, Interrupt Disable: %b",
                     cfg_bus_master_enable_dynamic, cfg_memory_space_enable_dynamic, cfg_interrupt_disable_dynamic);
            prev_pcileech_command = pcileech_command;
        end
    end
`endif

endmodule