http {
    lua_package_path "/path/to/lua/?.lua;;";

    # 在 http 级别初始化 metrics 共享字典
    lua_shared_dict metrics 10m;

    init_by_lua_block {
        local metrics = require "metrics"
        metrics.init(ngx.shared.metrics)
    }

    log_format json_combined escape=json
        '{'
            '"time_local":"$time_iso8601",'
            '"remote_addr":"$remote_addr",'
            '"request":"$request",'
            '"status":$status,'
            '"body_bytes_sent":$body_bytes_sent,'
            '"request_time":$request_time,'
            '"upstream_response_time":"$upstream_response_time",'
            '"http_referer":"$http_referer",'
            '"http_user_agent":"$http_user_agent"'
        '}';

    server {
        listen 80;
        server_name example.com;

        # 在 access 阶段设置请求开始时间
        set $request_start_time '';
        access_by_lua_block {
            ngx.var.request_start_time = ngx.now()
        }

        # 使用 Lua 自定义日志格式
        log_by_lua_block {
            local log_formatter = require "log_formatter"
            log_formatter.log(ngx)
        }

        location / {
            proxy_pass http://backend;
        }

        # 指标查询接口
        location /metrics {
            default_type text/plain;

            content_by_lua_block {
                local metrics = require "metrics"
                metrics.report(ngx)
            }
        }

        # 指标重置接口（可选，用于调试）
        location /metrics/reset {
            default_type text/plain;

            content_by_lua_block {
                local metrics = require "metrics"
                metrics.reset(ngx)
                ngx.say("metrics reset")
            }
        }
    }
}
