# scraper2_hj3415/app/nfs/services/fetch/common.py
from __future__ import annotations

import asyncio
from collections.abc import Awaitable

from logging_hj3415 import logger
from scraper2_hj3415.app.nfs.domain.doc import NfsDoc


async def gather_docs(
    coro_by_code: dict[str, Awaitable[NfsDoc | None]],
    *,
    endpoint: str,
) -> list[NfsDoc]:
    codes = list(coro_by_code.keys())
    results = await asyncio.gather(*coro_by_code.values(), return_exceptions=True)

    out: list[NfsDoc] = []
    for code, r in zip(codes, results):
        if isinstance(r, BaseException):
            logger.warning(
                f"{endpoint} fetch failed: code={code} err={type(r).__name__} msg={str(r)}"
            )
            continue
        if r is None:
            continue
        out.append(r)
    return out
