# app/src/bootstrap/app_factory.py

from __future__ import annotations

from aiogram import Bot, Dispatcher
from aiogram.client.default import DefaultBotProperties

from src.bootstrap.logging import setup_logging
from src.core.config import load_settings
from src.notifications.targets import NotificationTargetRegistry
from src.storage.schema import init_schema
from src.telegram.routers import setup_routers
from src.trading.journal.service import JournalService


def create_app() -> tuple[Bot, Dispatcher]:
    settings = load_settings()

    setup_logging(settings.log_level)

    journal = JournalService()

    try:
        init_schema()
    except Exception as exc:
        try:
            journal.log_critical(
                "app_bootstrap_failed",
                f"Не удалось инициализировать схему БД: {exc}",
                {
                    "env": settings.app_env,
                    "exchange_name": settings.exchange_name,
                    "default_symbol": settings.default_symbol,
                },
            )
        except Exception:
            pass
        raise

    try:
        journal.log_info(
            "app_started",
            "Приложение запущено",
            {
                "env": settings.app_env,
                "exchange_name": settings.exchange_name,
                "default_symbol": settings.default_symbol,
            },
        )
    except Exception:
        pass

    bot = Bot(
        token=settings.bot_token,
        default=DefaultBotProperties(parse_mode=settings.bot_parse_mode),
    )

    NotificationTargetRegistry.set_bot(bot)

    dispatcher = Dispatcher()

    setup_routers(dispatcher)

    return bot, dispatcher