#!/usr/bin/env python3
# Copyright: 2026, 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.

"""File-to-group policy: derive a group identity from a tree node.

These functions *read* a tree node (FileInfo/DirInfo) to compute the license
key, splitting path, and group key, rather than that policy living on the node
itself. Keeping it here lets the tree carry data and shape only.
"""

from __future__ import annotations

import typing as t
from collections import abc

from decopy.common.core_types import UNKNOWN, UNKNOWN_COPYRIGHTED
from decopy.grouping.grouping import GroupKey, make_group_key
from decopy.grouping.grouping_strategy import grouping_strategy_for

if t.TYPE_CHECKING:
    from decopy.common.core_types import Options
    from decopy.fstree.nodes import FileInfo


def license_key(node: FileInfo) -> str:
    """Resolve the license identifier for a node, in precedence order:

    1. An explicit (non-wildcarded) entry in debian/copyright.
    2. The license detected when parsing the file.
    3. The wildcarded license stored in debian/copyright.
    4. The license of the containing directory (recursively).

    Falls back to UNKNOWN_COPYRIGHTED when copyrights are present, else UNKNOWN.
    """
    if node.existing_group and node.fullname == node.matching_pattern:
        return node.existing_group.get_license_key()
    if node.effective_license:
        return node.effective_license
    if node.existing_group:
        return node.existing_group.get_license_key()
    if node.parent:
        return license_key(node.parent)
    if node.copyrights:
        return UNKNOWN_COPYRIGHTED
    return UNKNOWN


def _from_files(filenames: set[str]) -> str:
    """Provenance phrase naming the license file(s) a license came from."""
    return "from {}".format(", ".join(sorted(filenames)))


def _detected_source(node: FileInfo) -> str | None:
    """Phrase for a node's own detected license, or None when it has none."""
    if not node.licenses:
        return None
    if node.license_filenames:
        return _from_files(node.license_filenames)
    return f"detected in {node.fullname}"


def _inherited_source(node: FileInfo | None) -> str | None:
    """Phrase for a license inherited from the nearest ancestor that holds one,
    or None when no ancestor contributes a license. A license from a separate
    file names that file (more precise than the directory)."""
    while node is not None:
        if node.licenses:
            if node.license_filenames:
                return _from_files(node.license_filenames)
            return f"inherited from {node.fullname}/"
        node = node.parent
    return None


def license_source(node: FileInfo) -> str:
    """Describe where a node's license came from, mirroring license_key's
    precedence: the file's own detection, a separate license file, an ancestor
    directory, else none. Names a file or directory, so --spdx never applies.
    """
    own = _detected_source(node)
    if own is not None:
        return own
    inherited = _inherited_source(node.parent)
    if inherited is not None:
        return inherited
    if node.copyrights:
        return "copyright present, no license"
    return "no license detected"


def holder_sources(files: abc.Iterable[FileInfo]) -> dict[str, tuple[str, ...]]:
    """Map each copyright holder to the sorted files it was detected in.

    The key is the holder's ``email or person``, matching CopyrightHolders.key(),
    so it lines up with the holder strings the explain +/- lines render. The
    caller chooses which files to pass (e.g. excluding packaging files).
    """
    sources: dict[str, set[str]] = {}
    for fileinfo in files:
        for holder in fileinfo.copyrights:
            key = holder.email or holder.person
            sources.setdefault(key, set()).add(fileinfo.fullname)
    return {key: tuple(sorted(paths)) for key, paths in sources.items()}


def splitting_path(node: FileInfo, options: Options) -> str | None:
    """Path identifier used to split files into groups.

    Delegates to the active grouping strategy, which owns the
    --split-on-license / --split-debian rules.
    """
    return grouping_strategy_for(options.group_by).splitting_path(node, options)


def group_key(node: FileInfo, options: Options) -> GroupKey:
    """Assemble the (license, copyright, path) group key for a node."""
    return make_group_key(
        license_key(node),
        node.copyrights.key(),
        splitting_path(node, options),
        options,
    )
