from quart_common.web.request import (
  get_ip,
  get_my_ip_address,
  get_local_ip_addresses,
  generate_all_ips,
  replace_last_ip_segment,
  get_request_context,
  is_valid_uuid,
)
from quart_common.web.env import is_development_environment, is_testing_environment

from flask_limiter import Limiter

# Limiter Key Gen
def custom_limit_key():
  ip = get_ip()
  # if THE_IP_BOT_MANAGER.is_client_ip_always_allowed(ip):
  #   return None  # No key, no increment, no enforcement
  parts = [part for part in ip.split(':') if part]  # remove empty parts caused by ::
  return f":{'.'.join(parts)}:"

def enforce_custom_limit(limiter:Limiter, key:str, limit_count: int = 3, window_sec: int = 60):
  custom_key = custom_limit_key()
  if custom_key is None:
    return None

  key = f"{key}{custom_key.rstrip(':')}"

  current = limiter.storage.incr(key, expiry=window_sec)
  if current > limit_count:
    raise LookupError("To Many 404 Requests")
