import uuid

import redis as redis_lib
from fastapi import Depends, HTTPException, Request, status

from app.core.config import settings
from app.db.redis import get_redis


def _check(redis: redis_lib.Redis, key: str, limit: int, window_seconds: int) -> None:
    """Fixed-window counter: at most `limit` calls to this key per
    `window_seconds`. A single INCR (atomic in Redis) plus an EXPIRE
    set only on the first call in a window is enough here — no Lua
    script needed for a counter this simple."""
    count = redis.incr(key)
    if count == 1:
        redis.expire(key, window_seconds)
    if count > limit:
        ttl = redis.ttl(key)
        raise HTTPException(
            status_code=status.HTTP_429_TOO_MANY_REQUESTS,
            detail="Too many requests. Try again later.",
            headers={"Retry-After": str(max(ttl, 1))},
        )


def rate_limit_by_ip_and_phone(
    redis: redis_lib.Redis, request: Request, phone: str, action: str
) -> None:
    """Throttle an auth action independently by client IP (protects the
    server from one client hammering any account) and by phone
    (protects one phone number from being spammed with OTPs/login
    attempts from many IPs). `action` scopes the counters to a specific
    endpoint, e.g. "login" or "signup_start", so they don't share a
    bucket with unrelated endpoints. Takes the redis client as a
    parameter (callers get it via Depends(get_redis)) rather than
    fetching the module-level client itself, so tests can override it
    with an isolated fake per test — see tests/conftest.py."""
    ip = request.client.host if request.client else "unknown"
    limit = settings.rate_limit_max_attempts
    window = settings.rate_limit_window_seconds
    _check(redis, f"ratelimit:{action}:ip:{ip}", limit, window)
    _check(redis, f"ratelimit:{action}:phone:{phone}", limit, window)


def rate_limit_by_user(
    redis: redis_lib.Redis,
    user_id: uuid.UUID,
    action: str,
    limit: int,
    window_seconds: int,
) -> None:
    """Per-account throttle for an authenticated, abuse/cost-prone
    endpoint (checkout, image upload) — keyed by user id rather than
    IP, since these callers are always authenticated and IP-based
    limiting is both easy to route around (many accounts behind one
    IP, e.g. a shared network) and easy to trip by accident (many
    legitimate users behind one IP). On top of, not instead of,
    rate_limit_global."""
    _check(redis, f"ratelimit:{action}:user:{user_id}", limit, window_seconds)


# Health checks are polled frequently and legitimately by load
# balancers/uptime monitors — never worth throttling.
_EXEMPT_PATH_PREFIXES = ("/api/v1/health",)


def rate_limit_global(
    request: Request, redis: redis_lib.Redis = Depends(get_redis)
) -> None:
    """A broad backstop against one IP hammering *any* endpoint, not
    just the auth-specific actions rate_limit_by_ip_and_phone already
    covers with tighter, per-action limits — applied to the whole API
    router (see app.main), on top of those, not instead of them.
    Deliberately generous (see global_rate_limit_max_requests/
    global_rate_limit_window_seconds in config) since it's a
    last-resort net, not the primary defense on any specific
    endpoint."""
    if request.url.path.startswith(_EXEMPT_PATH_PREFIXES):
        return
    ip = request.client.host if request.client else "unknown"
    _check(
        redis,
        f"ratelimit:global:ip:{ip}",
        settings.global_rate_limit_max_requests,
        settings.global_rate_limit_window_seconds,
    )
