import pandas as pd
import pyarrow as pa
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.responses import PlainTextResponse

from n6k_server.routes import tables


def create_app() -> FastAPI:
    application = FastAPI()
    application.state.data_sources = {}

    application.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_methods=["*"],
        allow_headers=["*"],
    )

    @application.exception_handler(StarletteHTTPException)
    async def http_exception_handler(
        request: Request, exc: StarletteHTTPException
    ) -> PlainTextResponse:
        return PlainTextResponse(exc.detail, status_code=exc.status_code)

    @application.exception_handler(Exception)
    async def plain_text_exception_handler(
        request: Request, exc: Exception
    ) -> PlainTextResponse:
        status = getattr(exc, "status_code", 500)
        return PlainTextResponse(str(exc), status_code=status)

    application.include_router(tables.router, prefix="/tables")

    return application


def data(app: FastAPI, name: str):
    def decorator(fn):
        app.state.data_sources[name] = fn
        return fn
    return decorator
