#!/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.

"""Shared grouping vocabulary: the group key type and its assembly rule.

A group key is the (license, copyright, path) triple that decides which files
land in the same copyright paragraph. Both the per-file view (tree.FileInfo)
and the per-group view (group.Group) must build it the same way, so the
single assembly rule lives here rather than being duplicated in each.
"""

from __future__ import annotations

import typing as t

from decopy.grouping.grouping_strategy import grouping_strategy_for

if t.TYPE_CHECKING:
    from decopy.common.core_types import Options


class GroupKey(t.NamedTuple):
    """The (license, copyright, path) triple that decides paragraph membership.

    A NamedTuple, so the slots read as ``key.license`` / ``key.copyright`` /
    ``key.path`` rather than ``key[0..2]``, while staying a plain tuple for
    equality, hashing and use as a dict key.
    """

    license: str
    copyright: tuple[str, ...] | None
    path: str | None


def make_group_key(
    license_key: str,
    copyright_key: tuple[str, ...],
    path_key: str | None,
    options: Options,
) -> GroupKey:
    """Assemble a group key from its parts, applying the grouping policy.

    The copyright slot is filled only when grouping by copyright; otherwise it
    is None. Keeping this rule in one place ensures files and groups always
    agree on the key shape.
    """
    strategy = grouping_strategy_for(options.group_by)
    return GroupKey(
        license_key,
        strategy.key_copyright_slot(copyright_key),
        path_key,
    )
