from __future__ import annotations

import asyncio
import unittest

from app.http_limits import RequestBodyLimitMiddleware


def run_asgi_request(chunks: list[bytes], *, max_bytes: int, content_length: int | None = None):
    messages = [
        {
            "type": "http.request",
            "body": chunk,
            "more_body": index < len(chunks) - 1,
        }
        for index, chunk in enumerate(chunks)
    ]
    messages.append({"type": "http.disconnect"})
    sent: list[dict] = []
    app_calls: list[bytes] = []

    async def app(scope, receive, send):
        message = await receive()
        app_calls.append(message.get("body", b""))
        await send({"type": "http.response.start", "status": 204, "headers": []})
        await send({"type": "http.response.body", "body": b""})

    async def receive():
        return messages.pop(0)

    async def send(message):
        sent.append(message)

    headers = [] if content_length is None else [(b"content-length", str(content_length).encode())]
    scope = {
        "type": "http",
        "method": "POST",
        "path": "/api/solve",
        "headers": headers,
    }
    middleware = RequestBodyLimitMiddleware(app, max_bytes=max_bytes)
    asyncio.run(middleware(scope, receive, send))
    return sent, app_calls


class HttpLimitTests(unittest.TestCase):
    def test_fragmented_body_is_rejected_before_application_runs(self) -> None:
        sent, app_calls = run_asgi_request([b"1234", b"5678"], max_bytes=5)
        self.assertEqual(sent[0]["status"], 413)
        self.assertEqual(app_calls, [])

    def test_body_is_replayed_as_one_message_when_within_limit(self) -> None:
        sent, app_calls = run_asgi_request([b"1234", b"5"], max_bytes=5)
        self.assertEqual(sent[0]["status"], 204)
        self.assertEqual(app_calls, [b"12345"])

    def test_oversized_content_length_is_rejected_without_reading_body(self) -> None:
        sent, app_calls = run_asgi_request([b""], max_bytes=5, content_length=6)
        self.assertEqual(sent[0]["status"], 413)
        self.assertEqual(app_calls, [])

    def test_route_specific_limit_is_applied_before_validation(self) -> None:
        messages = [
            {"type": "http.request", "body": b"12345", "more_body": False},
            {"type": "http.disconnect"},
        ]
        sent: list[dict] = []
        app_calls: list[bool] = []

        async def app(scope, receive, send):
            app_calls.append(True)

        async def receive():
            return messages.pop(0)

        async def send(message):
            sent.append(message)

        scope = {"type": "http", "method": "POST", "path": "/api/solve", "headers": []}
        middleware = RequestBodyLimitMiddleware(
            app,
            max_bytes=10,
            path_limits={"/api/solve": 4},
        )
        asyncio.run(middleware(scope, receive, send))
        self.assertEqual(sent[0]["status"], 413)
        self.assertEqual(app_calls, [])


if __name__ == "__main__":
    unittest.main()
