import asyncio
import os
from pathlib import Path

import inject
from litestar import (
    Litestar,
)
from litestar.contrib.jinja import JinjaTemplateEngine
from litestar.static_files import create_static_files_router
from litestar.template.config import TemplateConfig

from server.config import get_app_config
from server.infra.db import AsyncDB
from server.infra.web import AtachmentController, BreedsController, DescriptionController, SeoController, VoteController
from server.modules.attachments import AtachmentService, DBAttachmentRepository, S3StorageDriver
from server.modules.descriptions import CharactersService, PGCharactersRepository
from server.modules.rate import PGVoteRepository, VotesService
from server.modules.recognizer import RecognizerRepository, RecognizerService

os.environ["CUDA_VISIBLE_DEVICES"] = "-1"


loop = asyncio.new_event_loop()


def inject_config(binder: inject.Binder):
    """initialization inject_config for server FastApi"""

    cnf = get_app_config()
    db = AsyncDB(cnf)
    loop.run_until_complete(db.connect())
    attach_service = AtachmentService(S3StorageDriver(cnf=cnf), DBAttachmentRepository(db))
    characters_repository = PGCharactersRepository(db)
    binder.bind(RecognizerService, RecognizerService(RecognizerRepository(db), attach_service, characters_repository))
    binder.bind(CharactersService, CharactersService(characters_repository))
    binder.bind(VotesService, VotesService(PGVoteRepository(db)))
    binder.bind(AtachmentService, attach_service)


inject.configure(inject_config)
app = Litestar(
    debug=True,
    route_handlers=[
        BreedsController,
        DescriptionController,
        SeoController,
        VoteController,
        AtachmentController,
        create_static_files_router(path="/static", directories=["server/static"]),
    ],
    template_config=TemplateConfig(
        directory=Path("server/templates"),
        engine=JinjaTemplateEngine,
    ),
)
