from __future__ import annotations

import logging
from collections.abc import Iterable
from typing import Any

from .iocs.text_parser import ParseResult, TextIOCParser


logger = logging.getLogger(__name__)
_parser = TextIOCParser()


def _select_bucket(result: ParseResult) -> str:
    indicator = result.indicator
    if indicator.category == "ip":
        if "ipv4" in indicator.kinds:
            return "ipv4"
        return indicator.category
    if indicator.category == "url":
        return "url"
    if indicator.category == "hash":
        return getattr(indicator, "algorithm", "hash")
    if indicator.category == "domain":
        return "domain"
    kinds = sorted(indicator.kinds)
    if kinds:
        return kinds[0]
    return indicator.category


async def parse_text(text: str) -> dict[str, list[str]]:
    """Разобрать значения IOC из переданного текста."""

    logger.info("Разбираем текст IOC длиной %d", len(text))
    results = _parser.parse(text)
    aggregated: dict[str, list[str]] = {}
    for result in results:
        bucket = _select_bucket(result)
        aggregated.setdefault(bucket, []).append(result.indicator.value)
    logger.debug("Агрегированные результаты парсинга: %s", aggregated)
    logger.info("Обнаружено %d индикатор(ов)", len(results))
    return aggregated
