"""This file provides the ability to combine vulnerabilities from multiple sources into a single model.

--------------------------------------------------------------------------------
SPDX-FileCopyrightText: Copyright © 2022 Lockheed Martin <open.source@lmco.com>
SPDX-FileName: hopprcop/vulnerability_combiner.py
SPDX-FileType: SOURCE
SPDX-License-Identifier: MIT
--------------------------------------------------------------------------------
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
--------------------------------------------------------------------------------
"""

from __future__ import annotations

from typing import TYPE_CHECKING

from typing_extensions import deprecated


if TYPE_CHECKING:
    from hoppr import Vulnerability


def _get_all_ids_from_vulnerability(from_vulnerability: Vulnerability) -> list[str]:
    ids: list[str] = [from_vulnerability.id] if from_vulnerability.id else []

    if from_vulnerability.references is not None:
        ids.extend(reference.id for reference in from_vulnerability.references)

    return list(set(ids))


def _does_id_exist_in_both(existing_id_list: list[str], new_id_list: list[str]) -> bool:
    return len([value for value in existing_id_list if value in new_id_list]) > 0


def _get_matching_vulnerability_from_list(
    combined_list: list[Vulnerability], new_finding: Vulnerability
) -> Vulnerability | None:
    new_finding_ids = _get_all_ids_from_vulnerability(new_finding)
    for vuln in combined_list:
        existing_finding_ids = _get_all_ids_from_vulnerability(vuln)

        if _does_id_exist_in_both(existing_finding_ids, new_finding_ids):
            return vuln

    return None


def merge_scanner_vulnerabilities(
    scanner_vulns: dict[str, list[Vulnerability]],
) -> list[Vulnerability]:
    """Intelligently combines the lists of vulnerabilities found by different scanners."""
    combined_result: list[Vulnerability] = []

    for vulns in scanner_vulns.values():
        for vulnerability in vulns:
            if existing := _get_matching_vulnerability_from_list(combined_result, vulnerability):
                existing.merge(vulnerability)
            else:
                combined_result.append(vulnerability)

    return combined_result


@deprecated(
    "vulnerability_combiner.combine_vulnerabilities is deprecated, use vulnerability_combiner.merge_scanner_vulnerabilities"
)
def combine_vulnerabilities(
    vulnerabilities_list: list[dict[str, list[Vulnerability]]],
) -> dict[str, list[Vulnerability]]:
    """Intelligently combines the lists of vulnerabilities found by different scanners."""
    combined_result: dict[str, list[Vulnerability]] = {}

    for result in vulnerabilities_list:
        for purl in result:
            tool_vulnerabilities = result.get(purl)

            if purl not in combined_result:
                combined_result[purl] = []

            for vulnerability in tool_vulnerabilities or []:
                if existing := _get_matching_vulnerability_from_list(combined_result[purl], vulnerability):
                    existing.merge(vulnerability)
                else:
                    combined_result[purl].append(vulnerability)

    return combined_result
