#!/usr/bin/env python3
#
# Copyright: 2016, Maximiliano Curia <maxy@debian.org>
#
# License: ISC
#  Permission to use, copy, modify, and/or distribute this software for any
#  purpose with or without fee is hereby granted, provided that the above
#  copyright notice and this permission notice appear in all copies.
#  .
#  THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
#  REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
#  AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
#  INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
#  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
#  OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
#  PERFORMANCE OF THIS SOFTWARE.

"""Generic functions used by the parsers."""

from __future__ import annotations

import collections.abc as abc

# Local modules
from .license_parsers import parse_exceptions
from .license_prefilter import candidate_indices
from .license_subs import COMMENTS_SUBS
from .res import COMPILED_RES, LICENSES_RES


def clean_comments(text: str) -> str:
    # replace it's way cheaper than re.sub
    for comment in (
        # C
        "/*",
        "*/",
        # Lisp
        ";;",
        # (HT|X)ML
        "<!--",
        "-->",
    ):
        text = text.replace(comment, " ")
    for comment_sub in COMMENTS_SUBS:
        text = comment_sub.pattern.sub(comment_sub.repl, text)

    return text


def find_licenses(text: str) -> abc.ValuesView[str]:
    """Scan the text for presence of any of the supported licenses.

    Returns:
        A list of the license ids found in the text.
    """
    licenses: dict[str, str] = {}
    suppressed: set[str] = set()

    # Skip rules whose necessary literal is absent: their search would fail
    # anyway, so the result is identical (None -> prefilter unavailable, run all).
    candidates = candidate_indices(text)

    for i, license_re in enumerate(LICENSES_RES):
        # Keep the license name in this frame for easier debugging
        license_: str | None = license_re.license
        family = license_re.license

        if family in licenses or family in suppressed:
            continue
        if candidates is not None and i not in candidates:
            continue
        match = COMPILED_RES[i].search(text)
        if not match:
            continue

        if license_re.get_detail:
            license_ = license_re.get_detail(text, match, family)

        # A rule may suppress its whole family (return None) when it recognises
        # an aggregate that should be reported under a single id from another
        # family (e.g. Net-SNMP). No later rule for this family is consulted.
        if license_ is None:
            suppressed.add(family)
            continue

        # Apply the matched rule's exception SUBS (carried as row data in res.py).
        if license_re.exception_subs is not None:
            license_ = parse_exceptions(text, license_, license_re.exception_subs)

        # A matcher may decline (return "") when its anchor fired but the text
        # lacks the distinctive content; keep looking rather than record a blank.
        if license_:
            licenses[family] = license_

    return licenses.values()
