"""
Debug middleware для логирования всех запросов
"""
import json
import time
from fastapi import Request
from fastapi.responses import Response

class DebugMiddleware:
    def __init__(self, app):
        self.app = app

    async def __call__(self, scope, receive, send):
        if scope["type"] == "http":
            request = Request(scope, receive)
            
            # Логируем только PUT запросы к admin/table
            if (request.method == "PUT" and 
                "admin/table" in str(request.url)):
                
                print(f"\n🔥 DEBUG: Incoming PUT request")
                print(f"📍 URL: {request.url}")
                print(f"📋 Headers: {dict(request.headers)}")
                
                # Читаем тело запроса
                body = await request.body()
                if body:
                    try:
                        json_data = json.loads(body.decode())
                        print(f"📦 Body: {json.dumps(json_data, indent=2, ensure_ascii=False)}")
                        print(f"📊 Types: {[(k, type(v).__name__) for k, v in json_data.items()]}")
                    except Exception as e:
                        print(f"📦 Raw body: {body}")
                        print(f"❌ JSON parse error: {e}")
                
                print(f"⏰ Time: {time.strftime('%H:%M:%S')}")
                print("=" * 60)
                
                # Создаем новый receive который правильно передает тело
                original_receive = receive
                body_sent = False
                
                async def new_receive():
                    nonlocal body_sent
                    if not body_sent:
                        body_sent = True
                        return {"type": "http.request", "body": body, "more_body": False}
                    else:
                        return await original_receive()
                
                # Обновляем receive
                receive = new_receive
                
        await self.app(scope, receive, send)