#!/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 .core_types import UNKNOWN, UNKNOWN_COPYRIGHTED
from .grouping import GroupKey, make_group_key
from .grouping_strategy import grouping_strategy_for

if t.TYPE_CHECKING:
    from .core_types import Options
    from .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 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).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,
    )
