// 系统监视器 - SoC运行状态监视
module system_monitor #(
    parameter GRID_W = 256,
    parameter GRID_H = 256
)(
    input  wire             clk,
    input  wire             rst_n,
    input  wire             ca_running,
    input  wire [31:0]      ca_steps,
    input  wire [31:0]      ca_population,
    input  wire             vga_active,
    input  wire             uart_activity,
    output wire [31:0]      uptime_cycles,
    output wire [15:0]      steps_per_second,
    output wire [7:0]       system_status,  // bit flags
    output wire             watchdog_ok
);
    reg [31:0] cycle_cnt;
    reg [31:0] last_step_cnt;
    reg [15:0] sps;
    reg [31:0] sps_timer;
    
    always @(posedge clk or negedge rst_n) begin
        if (!rst_n) begin
            cycle_cnt <= 32'd0;
            last_step_cnt <= 32'd0;
            sps <= 16'd0;
            sps_timer <= 32'd0;
        end else begin
            cycle_cnt <= cycle_cnt + 32'd1;
            sps_timer <= sps_timer + 32'd1;
            
            // 每秒计算一次SPS
            if (sps_timer >= 32'd100_000_000) begin
                sps <= (ca_steps - last_step_cnt)[15:0];
                last_step_cnt <= ca_steps;
                sps_timer <= 32'd0;
            end
        end
    end
    
    assign uptime_cycles = cycle_cnt;
    assign steps_per_second = sps;
    assign system_status = {ca_running, vga_active, uart_activity, 5'd0};
    assign watchdog_ok = (sps > 16'd0) || !ca_running;
endmodule