import contextlib

from fastapi import FastAPI, responses
from fastapi.exceptions import RequestValidationError
from shipaw.config import ShipawSettings
from shipaw.fapi.alerts import Alerts
from shipaw.fapi.app import request_validation_exception_handler
from shipaw.fapi.routes_api import router as shipaw_json_router
from shipaw.fapi.routes_html import router as shipaw_html_router
from starlette.requests import Request
from starlette.responses import HTMLResponse, RedirectResponse
from starlette.staticfiles import StaticFiles

from amship.back.ship_routes import router as ship_router


@contextlib.asynccontextmanager
async def lifespan(app_: FastAPI):
    try:
        # set_pf_env()
        # pythoncom.CoInitialize()
        # with sqm.Session(am_db.ENGINE) as session:
        #     pf_shipper = ELClient()
        #     populate_db_from_cmc(session, pf_shipper)
        yield

    finally:
        # pythoncom.CoUninitialize()

        ...


app = FastAPI(lifespan=lifespan)
app.mount('/static', StaticFiles(directory=str(ShipawSettings.from_env().static_dir)), name='static')
# app.mount('/static', StaticFiles(directory=str(amherst_settings().static_dir)), name='static')
app.include_router(ship_router, prefix='/shipaw')
app.include_router(shipaw_json_router, prefix='/shipaw/api')
app.include_router(shipaw_html_router, prefix='/shipaw')
# app.ship_live = pf_config.pf_sett().ship_live
app.alerts = Alerts.empty()


@app.exception_handler(RequestValidationError)
async def request_exception_handler(request: Request, exc: RequestValidationError):
    return await request_validation_exception_handler(request, exc)


@app.get('/robots.txt', response_class=responses.PlainTextResponse)
async def robots_txt() -> str:
    return 'User-agent: *\nAllow: /'


@app.get('/favicon.ico', include_in_schema=False)
async def favicon_ico():
    return responses.RedirectResponse(url='/static/favicon.svg')


@app.get('/', response_class=RedirectResponse)
async def startup(
    request: Request,
):
    if not hasattr(request.app, 'starting_url'):
        raise ValueError('App has no attribute starting_url')
    return RedirectResponse(request.app.starting_url)

