from __future__ import annotations

import traceback
from typing import Any, Callable

import allure  # pyright: ignore[reportMissingImports]
from allure_commons.types import AttachmentType  # pyright: ignore[reportMissingImports]


def before_scenario(context: Any, scenario: Any) -> None:  # noqa: ARG001
    # Стек очистки: функции вызываются в обратном порядке (LIFO).
    context._cleanup_fns: list[Callable[[], None]] = [] # type: ignore[attr-defined]


def after_scenario(context: Any, scenario: Any) -> None:  # noqa: ARG001
    cleanup_fns: list[Callable[[], None]] = getattr(context, "_cleanup_fns", [])
    while cleanup_fns:
        fn = cleanup_fns.pop()
        try:
            with allure.step(f"Cleanup: {getattr(fn, '__name__', 'cleanup')}"):
                fn()
        except Exception:
            # Cleanup не должен скрывать причину падения сценария, но полезно приложить traceback в Allure.
            allure.attach(
                traceback.format_exc(),
                name="Cleanup error",
                attachment_type=AttachmentType.TEXT,
            )

