const limit = Number(process.env.AGX_RATE_LIMIT_PER_MIN || 120);
const windowMs = 60 * 1000;
const buckets = new Map<string, { count: number; reset: number }>();

export function rateLimit(key: string) {
  const now = Date.now();
  const bucket = buckets.get(key);
  if (!bucket || bucket.reset < now) {
    buckets.set(key, { count: 1, reset: now + windowMs });
    return { ok: true, remaining: limit - 1 };
  }
  bucket.count += 1;
  return { ok: bucket.count <= limit, remaining: Math.max(0, limit - bucket.count) };
}
