local pushKey = GetConvar('shxrk_push_key', '')
local endpoint = GetConvar('shxrk_push_endpoint', 'https://api.shxrk.systems/api/v1/uptime/game-server/push')
local intervalSeconds = tonumber(GetConvar('shxrk_push_interval', '60')) or 60
if intervalSeconds < 15 then intervalSeconds = 15 end

if pushKey == '' then
    print('[shxrk-monitor] shxrk_push_key is not set — monitoring disabled. Add it to server.cfg')
    return
end

local tickDeltas = {}
local lastTick = GetGameTimer()

CreateThread(function()
    while true do
        Wait(0)
        local now = GetGameTimer()
        tickDeltas[#tickDeltas + 1] = now - lastTick
        if #tickDeltas > 600 then table.remove(tickDeltas, 1) end
        lastTick = now
    end
end)

local function serverFps()
    if #tickDeltas == 0 then return 0 end
    local total = 0
    for _, d in ipairs(tickDeltas) do total = total + d end
    local avg = total / #tickDeltas
    if avg <= 0 then return 0 end
    return math.floor((1000 / avg) + 0.5)
end

local function collectResources()
    local resources = {}
    local count = GetNumResources()
    for i = 0, count - 1 do
        local name = GetResourceByFindIndex(i)
        if name then
            resources[#resources + 1] = { name = name, state = GetResourceState(name) }
        end
    end
    return resources
end

local function pushMetrics()
    local payload = {
        player_count = GetNumPlayerIndices(),
        max_players = GetConvarInt('sv_maxclients', 48),
        fps = serverFps(),
        map_name = GetConvar('mapname', ''),
        server_name = GetConvar('sv_hostname', ''),
        resources = collectResources(),
    }
    PerformHttpRequest(endpoint, function(status)
        if status ~= 200 then
            print(('[shxrk-monitor] push failed: HTTP %s'):format(tostring(status)))
        end
    end, 'POST', json.encode(payload), {
        ['Content-Type'] = 'application/json',
        ['Authorization'] = 'Bearer ' .. pushKey,
    })
end

CreateThread(function()
    Wait(15000)
    print(('[shxrk-monitor] pushing metrics every %ds to %s'):format(intervalSeconds, endpoint))
    while true do
        pushMetrics()
        Wait(intervalSeconds * 1000)
    end
end)
