"""Application lifecycle hooks."""

from __future__ import annotations

import logging

from telegram.ext import Application

from bot.core.metrics import snapshot
from bot.infra.db.adapters import log_database_backend
from bot.infra.db.manager import db_manager
from bot.infra.db.memory_repository import memory_repository
from bot.runtime.cleanup import cleanup_caches, cleanup_runtime, cleanup_temp_files


logger = logging.getLogger(__name__)


async def on_start(application: Application) -> None:
    logger.info("Bobi runtime starting")

    log_database_backend()

    await db_manager.connect()
    await memory_repository.ensure_schema()

    me = await application.bot.get_me()
    logger.info("Connected as @%s (%s)", me.username, me.id)

    if application.job_queue:
        application.job_queue.run_repeating(cleanup_runtime, interval=1800, first=600)
        application.job_queue.run_repeating(cleanup_caches, interval=900, first=300)
        application.job_queue.run_repeating(cleanup_temp_files, interval=3600, first=1200)

        logger.info("Runtime cleanup jobs registered")


async def on_shutdown(application: Application) -> None:
    await db_manager.close()

    logger.info("Runtime metrics: %s", snapshot())
    logger.info("Bobi runtime shutting down")
