from __future__ import annotations

import asyncio
import logging
import os
from collections.abc import Sequence, Iterable
from pathlib import Path
from typing import Any, TYPE_CHECKING

from aiomultiprocess import Pool  # type:ignore[import]

from checkov.common.bridgecrew.vulnerability_scanning.integrations.package_scanning import PackageScanningIntegration

if TYPE_CHECKING:
    from checkov.common.bridgecrew.platform_integration import BcPlatformIntegration


async def _report_results_to_bridgecrew_async(
    scan_results: Iterable[dict[str, Any]],
    bc_integration: BcPlatformIntegration,
    bc_api_key: str,
) -> Sequence[int]:
    package_scanning_int = PackageScanningIntegration()
    args = [(result, bc_integration, bc_api_key, Path(result["repository"])) for result in scan_results]

    if os.getenv("PYCHARM_HOSTED") == "1":
        # PYCHARM_HOSTED env variable equals 1 when running via Pycharm.
        # it avoids us from crashing, which happens when using multiprocessing via Pycharm's debug-mode
        logging.warning("reporting the results in sequence for avoiding crashing when running via Pycharm")
        exit_codes = []
        for curr_arg in args:
            exit_codes.append(await package_scanning_int.report_results_async(*curr_arg))
    else:
        async with Pool() as pool:
            exit_codes = await pool.starmap(package_scanning_int.report_results_async, args)

    return exit_codes


def report_results_to_bridgecrew(
    scan_results: Iterable[dict[str, Any]],
    bc_integration: BcPlatformIntegration,
    bc_api_key: str,
) -> Sequence[int]:
    return asyncio.run(_report_results_to_bridgecrew_async(scan_results, bc_integration, bc_api_key))
