"""Runtime cleanup and maintenance jobs."""

from __future__ import annotations

import gc
import logging
from pathlib import Path
from time import time

from bot.core.metrics import incr
from bot.services.cache import botadmin_cache, locks_cache, privileged_cache, settings_cache


logger = logging.getLogger("bobi.cleanup")


TEMP_PATH = Path("temp")


async def cleanup_runtime(_: object = None) -> None:
    gc.collect()

    incr("cleanup.gc")

    logger.debug("Garbage collection completed")


async def cleanup_temp_files(_: object = None) -> None:
    if not TEMP_PATH.exists():
        return

    removed = 0
    now = time()

    for file in TEMP_PATH.glob("**/*"):
        if not file.is_file():
            continue

        try:
            age = now - file.stat().st_mtime

            if age > 3600:
                file.unlink(missing_ok=True)
                removed += 1

        except Exception as e:
            logger.warning("Cleanup failed for %s: %s", file, e)

    if removed:
        incr("cleanup.temp_files")

        logger.info("Removed %s stale temp files", removed)


async def cleanup_caches(_: object = None) -> None:
    settings_cache.expire()
    locks_cache.expire()
    privileged_cache.expire()
    botadmin_cache.expire()

    incr("cleanup.caches")
