import uvicorn
# import pathlib
import datetime
import uuid
from contextlib import asynccontextmanager

from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi_sitemap import SiteMap

from .database import create_tables, delete_tables
from .router import router as datings_router
from .validity import is_valid_uuid


from pydantic_settings import BaseSettings, SettingsConfigDict


class Settings(BaseSettings):
    OPENAPI_URL: str = "/openapi.json"

    model_config = SettingsConfigDict(
        env_file=(".env", ".env.local", ".env.prod"),
        env_file_encoding="utf-8",
        case_sensitive=True
    )


settings = Settings()


@asynccontextmanager
async def lifespan(app: FastAPI):
    await create_tables()
    print("База готова")
    yield
    # await delete_tables()
    # print("База очищена")
    print("Приложение завершено")


app = FastAPI(
    lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=settings.OPENAPI_URL
)

favicon_path = "static/assets/img/favicons/favicon.ico"

templates = Jinja2Templates(directory="templates")

app.include_router(datings_router)

app.mount("/static", StaticFiles(directory="static"), name="static")


@app.get("/", response_class=HTMLResponse)
async def index(request: Request):

    response = templates.TemplateResponse(
        "index.html", {"request": request}
    )
    sessionKey = request.cookies.get("sessionkey")
    if isinstance(sessionKey, str) and is_valid_uuid(sessionKey):
        pass
    else:
        days = 365
        expires_t_obj = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
            days=days
        )
        expires_t_str = expires_t_obj.strftime("%a, %d %b %Y %H:%M:%S GMT")

        response.set_cookie(
            key="sessionkey", value=str(uuid.uuid4()), expires=expires_t_str
        )
    return response


@app.get("/about_me", response_class=HTMLResponse)
async def about_me(request: Request):
    response = templates.TemplateResponse("about_me.html", {"request": request})
    sessionKey = request.cookies.get("sessionkey")
    if isinstance(sessionKey, str) and is_valid_uuid(sessionKey):
        pass
    else:
        days = 365
        expires_t_obj = datetime.datetime.now(
            datetime.timezone.utc
        ) + datetime.timedelta(days=days)
        expires_t_str = expires_t_obj.strftime("%a, %d %b %Y %H:%M:%S GMT")

        response.set_cookie(
            key="sessionkey", value=str(uuid.uuid4()), expires=expires_t_str
        )
    return response


@app.get("/about_site", response_class=HTMLResponse)
async def about_site(request: Request):
    response = templates.TemplateResponse("about_site.html", {"request": request})
    sessionKey = request.cookies.get("sessionkey")
    if isinstance(sessionKey, str) and is_valid_uuid(sessionKey):
        pass
    else:
        days = 365
        expires_t_obj = datetime.datetime.now(
            datetime.timezone.utc
        ) + datetime.timedelta(days=days)
        expires_t_str = expires_t_obj.strftime("%a, %d %b %Y %H:%M:%S GMT")

        response.set_cookie(
            key="sessionkey", value=str(uuid.uuid4()), expires=expires_t_str
        )
    return response


@app.get("/favicon.ico", include_in_schema=False)
async def favicon():
    return FileResponse(favicon_path)


@app.get("/robots.txt", response_class=PlainTextResponse)
def robots():
    data = """User-agent: *\nAllow: /\nSitemap: /sitemap.xml"""
    return data


@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
    return JSONResponse(status_code=exc.status_code, content={"detail": exc.detail})


sitemap = SiteMap(
    app=app,
    base_url="https://lerafoxqueen.ru",
    static_dirs=["static", "docs"],
    exclude_patterns=[
        "^/api/",
        "^/docs/",
        "^/datings",
        "^/api/",
        "^/admin/",
    ],  # optional: exclude patterns
    include_dynamic=True,
    changefreq="daily",
    priority_map={
        "/": 1.0,
    },
    gzip=True,  # optional: make a gz version too
)

sitemap.attach()  # now GET /sitemap.xml is live

# @sitemap.source
# def extra_urls():
#     yield URLInfo("https://lerafoxqueen.ru/sitemap.xml")


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8001)
