<reponame>kostya-ten/iperon
from __future__ import annotations

import asyncio
import logging
import os

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import ORJSONResponse
from tortoise import Tortoise

from . import __VERSION__, logger, handlers, redis, cron
from .exceptions import exception_handlers
from .settings import settings, ORM_CONFIG

app = FastAPI(
    title='Iperon',
    version=__VERSION__,
    default_response_class=ORJSONResponse,
    docs_url='/api/',
    redoc_url=None,
    openapi_url='/api/v1/openapi.json',
    debug=settings.debug,
    exception_handlers=exception_handlers,  # type: ignore
)

if not settings.debug:  # pragma: no cover
    app.redoc_url = None

# Initialization logger
logger.logger_init()

# Added middleware GZip
app.add_middleware(GZipMiddleware)

# Added CORS Middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        'http://localhost',
        'http://localhost:3000',
    ],
    allow_credentials=True,
    allow_methods=['*'],
    allow_headers=['*'],
)


async def db_init() -> None:
    # Initialization Tortoise
    # Waiting for a connection to the DB

    log = logging.getLogger('iperon')

    while True:
        try:
            await Tortoise.init(config=ORM_CONFIG)
        except ConnectionRefusedError as err:  # pragma: no cover
            log.critical(f'PostgresSQL connection error "{err}"')
            await asyncio.sleep(10)
            continue
        else:  # pragma: no cover
            break

    # Create schema
    if connection := Tortoise.get_connection('master'):
        await connection.execute_query(f'CREATE SCHEMA IF NOT EXISTS {settings.db_schema}')


async def db_shutdown() -> None:
    await Tortoise.close_connections()


@app.on_event('startup')
async def startup_event() -> None:
    log = logging.getLogger('iperon')

    await db_init()

    # Initialization redis
    await redis.RedisClient.init()

    # Startup crontab
    await cron.startup()

    log.info(f'Startup service pid:{os.getpid()}')


@app.on_event('shutdown')
async def shutdown_event() -> None:
    await db_shutdown()
    await redis.RedisClient.redis.close()


# Registration of routers
app.include_router(handlers.member.router, prefix='/api/v1')
app.include_router(handlers.organization.router, prefix='/api/v1')
app.include_router(handlers.healthcheck.router, prefix='/api/v1')

from __future__ import annotations

import asyncio
import logging
import os

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import ORJSONResponse
from tortoise import Tortoise

from . import __VERSION__, logger, handlers, redis, cron
from .exceptions import exception_handlers
from .settings import settings, ORM_CONFIG

app = FastAPI(
    title='Iperon',
    version=__VERSION__,
    default_response_class=ORJSONResponse,
    docs_url='/api/',
    redoc_url=None,
    openapi_url='/api/v1/openapi.json',
    debug=settings.debug,
    exception_handlers=exception_handlers,  # type: ignore
)

if not settings.debug:  # pragma: no cover
    app.redoc_url = None

# Initialization logger
logger.logger_init()

# Added middleware GZip
app.add_middleware(GZipMiddleware)

# Added CORS Middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        'http://localhost',
        'http://localhost:3000',
    ],
    allow_credentials=True,
    allow_methods=['*'],
    allow_headers=['*'],
)


async def db_init() -> None:
    # Initialization Tortoise
    # Waiting for a connection to the DB

    log = logging.getLogger('iperon')

    while True:
        try:
            await Tortoise.init(config=ORM_CONFIG)
        except ConnectionRefusedError as err:  # pragma: no cover
            log.critical(f'PostgresSQL connection error "{err}"')
            await asyncio.sleep(10)
            continue
        else:  # pragma: no cover
            break

    # Create schema
    if connection := Tortoise.get_connection('master'):
        await connection.execute_query(f'CREATE SCHEMA IF NOT EXISTS {settings.db_schema}')


async def db_shutdown() -> None:
    await Tortoise.close_connections()


@app.on_event('startup')
async def startup_event() -> None:
    log = logging.getLogger('iperon')

    await db_init()

    # Initialization redis
    await redis.RedisClient.init()

    # Startup crontab
    await cron.startup()

    log.info(f'Startup service pid:{os.getpid()}')


@app.on_event('shutdown')
async def shutdown_event() -> None:
    await db_shutdown()
    await redis.RedisClient.redis.close()


# Registration of routers
app.include_router(handlers.member.router, prefix='/api/v1')
app.include_router(handlers.organization.router, prefix='/api/v1')
app.include_router(handlers.healthcheck.router, prefix='/api/v1')
# type: ignore # pragma: no cover # Initialization logger # Added middleware GZip # Added CORS Middleware # Initialization Tortoise # Waiting for a connection to the DB # pragma: no cover # pragma: no cover # Create schema # Initialization redis # Startup crontab # Registration of routers