import redis
import time


redis_client = redis.Redis(
    host="localhost",
    port=6379,
    decode_responses=True
)


def check_velocity(ip, window_seconds=60, threshold=3):
    key = f"velocity:{ip}"

    current_time = time.time()
    window_start = current_time - window_seconds

    redis_client.zremrangebyscore(
        key,
        0,
        window_start
    )

    redis_client.zadd(
        key,
        {str(current_time): current_time}
    )

    redis_client.expire(key, window_seconds)

    request_count = redis_client.zcard(key)

    return {
        "request_count": request_count,
        "high_velocity": request_count >= threshold
    }

def check_duplicate(ip, user_agent, window_seconds=60):
    key = f"duplicate:{ip}:{user_agent}"

    is_duplicate = redis_client.exists(key)

    redis_client.setex(
        key,
        window_seconds,
        "1"
    )

    return {
        "duplicate": bool(is_duplicate)
    }

def check_blocked(ip, user_agent):
    ip = str(ip)
    user_agent = str(user_agent)

    key = f"blocked:{ip}:{user_agent}"

    return {
        "blocked": redis_client.exists(key)
    }


def store_blocked(ip, user_agent, risk_score, features):
    ip = str(ip)
    user_agent = str(user_agent)

    key = f"blocked:{ip}:{user_agent}"

    redis_client.hset(
        key,
        mapping={
            "ip": ip,
            "user_agent": user_agent,
            "risk_score": risk_score,
            "features": ",".join(features),
            "blocked_at": str(time.time())
        }
    )

    return True

def track_suspicious(ip, user_agent):
    ip = str(ip)
    user_agent = str(user_agent)

    key = f"suspicious:{ip}:{user_agent}"

    count = redis_client.hincrby(key, "count", 1)

    redis_client.hset(
        key,
        mapping={
            "ip": ip,
            "user_agent": user_agent,
            "last_seen": str(time.time())
        }
    )

    return {
        "suspicious_count": count
    }