"""真正启动 uvicorn 经 TCP 验证 FastAPI 生命周期与错误协议。"""
from contextlib import asynccontextmanager
import json
import socket
import threading
import time
from urllib.error import HTTPError
from urllib.request import Request, urlopen
from uuid import UUID, uuid4
from fastapi import FastAPI, HTTPException, Query, Request as APIRequest
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
import uvicorn


def create_app():
    @asynccontextmanager
    async def lifespan(app):
        app.state.events = [{"id": 1, "path": "/health"}, {"id": 2, "path": "/orders"}]
        app.state.started = True
        app.state.closed = False
        try:
            yield
        finally:
            app.state.events.clear()
            app.state.closed = True

    app = FastAPI(lifespan=lifespan)

    @app.middleware("http")
    async def request_id(request: APIRequest, call_next):
        incoming = request.headers.get("x-request-id", "")
        try:
            correlation = str(UUID(incoming))
        except (ValueError, AttributeError):
            correlation = str(uuid4())
        request.state.request_id = correlation
        response = await call_next(request)
        response.headers["x-request-id"] = correlation
        return response

    def error_response(request, status, code):
        return JSONResponse(status_code=status, content={"error": {
            "code": code, "request_id": request.state.request_id}})

    @app.exception_handler(RequestValidationError)
    async def validation_error(request, exc):
        return error_response(request, 422, "invalid_input")

    @app.exception_handler(StarletteHTTPException)
    async def business_error(request, exc):
        return error_response(request, exc.status_code, str(exc.detail))

    @app.get("/health")
    async def health():
        return {"ready": app.state.started}

    @app.get("/events")
    async def events(after: int = Query(0, ge=0), limit: int = Query(1, ge=1, le=100)):
        selected = [event for event in app.state.events if event["id"] > after][:limit]
        return {"items": selected, "next_after": selected[-1]["id"] if selected else None}

    @app.get("/events/{event_id}")
    async def event(event_id: int):
        for value in app.state.events:
            if value["id"] == event_id:
                return value
        raise HTTPException(status_code=404, detail="event_not_found")

    return app


def main():
    app = create_app()
    listener = socket.socket()
    listener.bind(("127.0.0.1", 0))
    listener.listen(16)
    port = listener.getsockname()[1]
    server = uvicorn.Server(uvicorn.Config(app, log_level="error", lifespan="on",
                                         workers=1, loop="asyncio", http="h11"))
    thread = threading.Thread(target=lambda: server.run(sockets=[listener]))
    thread.start()
    def get(path, correlation=None):
        headers = {"x-request-id": correlation} if correlation else {}
        request = Request(f"http://127.0.0.1:{port}{path}", headers=headers)
        try:
            response = urlopen(request, timeout=2)
        except HTTPError as exc:
            response = exc
        with response:
            return response.status, response.headers["x-request-id"], json.loads(response.read())
    try:
        deadline = time.monotonic() + 5
        while not server.started:
            if not thread.is_alive() or time.monotonic() >= deadline:
                raise RuntimeError("server startup failed")
            time.sleep(0.01)
        assert get("/health")[2] == {"ready": True}
        correlation = "00000000-0000-0000-0000-000000000001"
        status, echoed, first = get("/events?limit=1", correlation)
        assert status == 200 and echoed == correlation and first["next_after"] == 1
        assert get("/events")[2] == first  # 明确验证默认 after=0、limit=1。
        assert get("/events?after=1&limit=1")[2]["items"] == [{"id": 2, "path": "/orders"}]
        assert get("/events?after=2")[2] == {"items": [], "next_after": None}
        for path, expected_status, code in (("/events?limit=0", 422, "invalid_input"),
                                            ("/events/no-number", 422, "invalid_input"),
                                            ("/events/999", 404, "event_not_found"),
                                            ("/unknown", 404, "Not Found")):
            status, echoed, payload = get(path, correlation)
            assert (status, payload["error"]["code"], payload["error"]["request_id"]) == (
                expected_status, code, echoed)
        _, generated, _ = get("/health", "untrusted arbitrary text")
        assert str(UUID(generated)) == generated
    finally:
        server.should_exit = True
        thread.join(timeout=5)
        listener.close()
    assert not thread.is_alive()
    assert app.state.closed and app.state.events == []
    print("28 checks: real TCP; validation/paging/error IDs; startup/shutdown cleanup")


if __name__ == "__main__":
    main()
