"""Утилиты для запуска анализа индикаторов."""

from __future__ import annotations

import inspect
import logging
from typing import Any, Mapping

from ioc_checker.iocs import IOCType
from ioc_checker.iocs.analysis import default_verdict
from ioc_checker.iocs.reason_texts import (
    ANALYSIS_EMPTY_VERDICT_REASON,
    ANALYSIS_ERROR_REASON_TEMPLATE,
)

logger = logging.getLogger(__name__)


async def run_indicator_analysis(
    indicator: IOCType,
    provider_features: Mapping[str, Any] | None,
) -> dict[str, Any]:
    """Запустить анализ индикатора на основе готовых фич."""

    prepared_features = provider_features or {}
    logger.info("Запуск анализа индикатора %s", getattr(indicator, "value", indicator))
    try:
        analysis_result = indicator.analysis(prepared_features) or {}
        if inspect.isawaitable(analysis_result):
            analysis_result = await analysis_result
    except Exception as exc:  # noqa: BLE001
        logger.exception(
            "Анализ индикатора %s завершился с ошибкой: %s",
            getattr(indicator, "value", indicator),
            exc,
        )
        analysis_result = {
            "features": prepared_features,
            "status": "error",
            **default_verdict(
                ANALYSIS_ERROR_REASON_TEMPLATE.format(error=exc),
            ),
        }
    if "verdicts" not in analysis_result:
        analysis_result.update(default_verdict(ANALYSIS_EMPTY_VERDICT_REASON))
    analysis_result.setdefault("status", "ok")
    analysis_result.setdefault("features", prepared_features)
    analysis_result.setdefault("reasons", [])
    analysis_result.setdefault("tags", [])
    logger.debug(
        "Анализ индикатора %s завершён, результаты: %s",
        getattr(indicator, "value", indicator),
        analysis_result,
    )
    return analysis_result
