import socketio
from fastapi import FastAPI, APIRouter
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException
from starlette.responses import PlainTextResponse

# Game state
from server.ws import sio, lobby

# Server
app = FastAPI()
router = APIRouter()
#
# app.add_middleware(
#     CORSMiddleware,
#     allow_origins=["*"],
#     allow_credentials=True,
#     allow_methods=["*"],
#     allow_headers=["*"],
# )

# Create and mount SocketIO app
sio_asgi_app = socketio.ASGIApp(
    socketio_server=sio,
    other_asgi_app=app
)
app.add_route("/socket.io/", route=sio_asgi_app, methods=['GET', 'POST'])
app.add_websocket_route("/socket.io/", route=sio_asgi_app)


@router.get("/")
async def hello_world():
    return "Hello, gentle[wo]man"


@router.get("/reset")
async def reset(
):
    return await lobby.reset()


app.include_router(router)


@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
    return PlainTextResponse(str(exc.detail), status_code=exc.status_code)


@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
    return PlainTextResponse(str(exc), status_code=400)


if __name__ == '__main__':
    import uvicorn

    uvicorn.run("app:app", host="0.0.0.0", port=9042, reload=True)
