#!/usr/bin/env python3

import uvicorn
from fastapi import FastAPI

from .config import Config, Settings
from .db import Connection, schemas
from .routers import admin, user

settings = Settings.get()


api = FastAPI(
    title="kiwi-vpn API",
    description="This API enables the `kiwi-vpn` service.",
    contact={
        "name": "Jörn-Michael Miehe",
        "email": "40151420+ldericher@users.noreply.github.com",
    },
    license_info={
        "name": "MIT License",
        "url": "https://opensource.org/licenses/mit-license.php",
    },
    openapi_url=settings.openapi_url,
    docs_url=settings.docs_url if not settings.production_mode else None,
    redoc_url=settings.redoc_url if not settings.production_mode else None,
)

app = FastAPI()
app.mount("/api", api)

api.include_router(admin.router)
api.include_router(user.router)


@app.on_event("startup")
async def on_startup() -> None:
    if (current_config := await Config.load()) is not None:
        Connection.connect(await current_config.db.db_engine)

        # some testing
        with Connection.use() as db:
            print(schemas.User.from_db(db, "admin"))
            print(schemas.User.from_db(db, "nonexistent"))


def main() -> None:
    uvicorn.run(
        "kiwi_vpn_api.main:app",
        host="0.0.0.0",
        port=8000,
        reload=True,
    )


if __name__ == "__main__":
    main()