import httpx
from litestar import Litestar, get
from litestar.contrib.jinja import JinjaTemplateEngine
from litestar.di import Provide
from litestar.exceptions import HTTPException
from litestar.static_files import StaticFilesConfig
from litestar.template import TemplateConfig

from src.huesoporro.api.dependencies import (
    authenticate,
    get_authenticate_action,
    get_authenticator,
    get_chatbot_settings_svc,
    get_db,
    get_get_user_by_jwt_action,
    get_sentences_svc,
    get_settings,
    get_user_repo,
    store_chatbot_settings_svc,
)
from src.huesoporro.api.errors import (
    after_exception_handler,
    http_exception_handler,
    httpx_status_error_handler,
)
from src.huesoporro.api.routes.api import (
    get_bot_settings,
    get_bot_status,
    get_index,
    get_sentences,
    get_tts_overlay,
    get_tts_permalink,
    manage_bot,
    save_bot_settings,
    save_new_sentence,
)
from src.huesoporro.api.routes.auth import get_code, login
from src.huesoporro.bot import BotsManager
from src.huesoporro.settings import Settings


@get("/healthz")
def get_health() -> dict:
    return {"status": "ok"}


def create_app():
    return Litestar(
        route_handlers=[
            get_health,
            login,
            get_index,
            get_tts_overlay,
            get_tts_permalink,
            get_code,
            manage_bot,
            get_bot_status,
            save_bot_settings,
            get_bot_settings,
            get_sentences,
            save_new_sentence,
        ],
        static_files_config=(
            StaticFilesConfig(
                path="/tts_files",
                directories=[Settings.get().tts_cache_path],
            ),
            StaticFilesConfig(
                path="static",
                directories=[Settings.get().static_files_path],
            ),
        ),
        template_config=TemplateConfig(
            directory=Settings.get().templates_files_path,
            engine=JinjaTemplateEngine,
        ),
        exception_handlers={
            HTTPException: http_exception_handler,
            httpx.HTTPStatusError: httpx_status_error_handler,
        },
        after_exception=[after_exception_handler],
        dependencies={
            "s": Provide(get_settings, use_cache=True),
            "a": Provide(get_authenticator, use_cache=True),
            "user": Provide(authenticate),
            "db": Provide(get_db, use_cache=True),
            "bm": Provide(BotsManager, use_cache=True),
            "gbs": Provide(get_chatbot_settings_svc),
            "sbs": Provide(store_chatbot_settings_svc),
            "sgs": Provide(get_sentences_svc),
            "authenticator": Provide(get_authenticator),
            "authenticate_action": Provide(get_authenticate_action),
            "user_repo": Provide(get_user_repo),
            "get_user_by_jwt_action": Provide(get_get_user_by_jwt_action),
        },
    )


app = create_app()
