"""真实 FastAPI/uvicorn HTTP 与 lifespan，依赖版本见环境锁文件。"""
from contextlib import asynccontextmanager
import json
import socket
import threading
import time
from urllib.error import HTTPError
from urllib.request import urlopen

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
import uvicorn


def main():
    events = []
    errors = []

    @asynccontextmanager
    async def lifespan(app):
        events.append("startup")
        try:
            yield
        finally:
            events.append("shutdown")

    app = FastAPI(lifespan=lifespan)

    @app.get("/counts")
    async def counts(request: Request):
        values = request.query_params.getlist("limit") or ["10"]
        raw = values[0]
        if (len(values) != 1 or not raw.isascii() or not raw.isdecimal()
                or len(raw) > 3 or not 1 <= int(raw) <= 100):
            return JSONResponse({"error": "invalid limit"}, status_code=400)
        return {"limit": int(raw), "errors": 2}

    listener = socket.socket()
    listener.bind(("127.0.0.1", 0))
    port = listener.getsockname()[1]
    server = uvicorn.Server(uvicorn.Config(app, log_config=None, access_log=False,
                                          lifespan="on", timeout_graceful_shutdown=2))

    def serve():
        try:
            server.run(sockets=[listener])
        except BaseException as error:
            errors.append(error)

    worker = threading.Thread(target=serve)
    worker.start()
    try:
        deadline = time.monotonic() + 5
        while not server.started and worker.is_alive() and time.monotonic() < deadline:
            time.sleep(0.01)
        assert server.started, errors
        assert events == ["startup"]
        for query, expected in [("limit=3", 200), ("limit=0", 400),
                                ("limit=2&limit=3", 400)]:
            try:
                result = urlopen(f"http://127.0.0.1:{port}/counts?{query}", timeout=2)
            except HTTPError as error:
                result = error
            with result:
                assert result.code == expected
                print("HTTP:", result.code, json.loads(result.read()))
    finally:
        server.should_exit = True
        worker.join(timeout=5)
        listener.close()
    assert not worker.is_alive(), "server did not stop"
    assert not errors, errors
    assert events == ["startup", "shutdown"]
    print("lifespan:", events)


if __name__ == "__main__":
    main()
