import sys

content = open('app/api/middleware/security_middleware.py', 'r', encoding='utf-8').read()

middleware_code = '''
from collections import defaultdict, deque
import time

class SimpleGlobalRateLimitMiddleware(BaseHTTPMiddleware):
    """Global Rate Limiter (Sliding Window Memory) to prevent DDoS/Bruteforce."""
    def __init__(self, app, max_requests: int = 60, window_seconds: int = 60):
        super().__init__(app)
        self.max_requests = max_requests
        self.window_seconds = window_seconds
        self.ip_records = defaultdict(deque)

    async def dispatch(self, request: Request, call_next):
        # Bypass static files
        if request.url.path.startswith("/static") or request.url.path.startswith("/storage"):
            return await call_next(request)
            
        ip = request.client.host if request.client else "unknown"
        now = time.time()
        
        history = self.ip_records[ip]
        while history and history[0] < now - self.window_seconds:
            history.popleft()
            
        if len(history) >= self.max_requests:
            logger.warning(f"[RATE LIMIT] Blocked IP {ip} - Exceeded {self.max_requests} req / {self.window_seconds}s")
            return JSONResponse(
                status_code=429, 
                content={
                    "status": "error",
                    "error_code": "TOO_MANY_REQUESTS", 
                    "message": f"Hệ thống đang chịu tải cao. Vui lòng thử lại sau {self.window_seconds} giây."
                }
            )
            
        history.append(now)
        return await call_next(request)
'''

open('app/api/middleware/security_middleware.py', 'a', encoding='utf-8').write(middleware_code)
print("Appended RateLimit middleware")
