-- Answer every request with an error and (optionally) a retry hint.
-- STATUS=429|503   HDR="Retry-After"   VAL="2" | "date+5" | "soon" | ...
local status = tonumber(os.getenv("STATUS") or "429")
local hdr = os.getenv("HDR") or ""
local val = os.getenv("VAL") or ""

local bodies = {
  ["api.openai.com"] = '{"error":{"message":"Rate limit reached","type":"requests","code":"rate_limit_exceeded"}}',
  ["api.anthropic.com"] = '{"type":"error","error":{"type":"rate_limit_error","message":"Rate limited"}}',
  ["amazonaws.com"] = '{"__type":"com.amazonaws.dynamodb.v20120810#ThrottlingException","message":"Rate exceeded"}',
  ["api.stripe.com"] = '{"error":{"type":"invalid_request_error","code":"rate_limit","message":"Too many requests"}}',
  ["googleapis.com"] = '{"error":{"code":429,"message":"Resource exhausted","status":"RESOURCE_EXHAUSTED"}}',
  ["api.github.com"] = '{"message":"API rate limit exceeded","documentation_url":"https://docs.github.com/rest"}',
}

function on_request(request)
  local body, ctype = '{"error":"slow down"}', "application/json"
  for host, b in pairs(bodies) do
    if string.find(request.url, host, 1, true) then body = b end
  end
  if string.find(request.url, "amazonaws.com", 1, true) then ctype = "application/x-amz-json-1.0" end
  local headers = { ["Content-Type"] = ctype }
  if hdr ~= "" then
    local v = val
    local secs = string.match(val, "^date%+(%d+)$")
    if secs then v = os.date("!%a, %d %b %Y %H:%M:%S GMT", os.time() + tonumber(secs)) end
    headers[hdr] = v
  end
  return { status = status, headers = headers, body = body }
end
