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

"""find_licenses() de-duplicates names produced by more than one rule family.

Different LICENSES_RES families are keyed separately, so two of them can resolve
to the *same* DEP-5 name and the raw result would repeat it -- a disjunction like
"CC-BY-4 or CC-BY-4". The detected names are already canonical, so identical
names are the same licence and must collapse to one member.
"""

import json
import unittest
from pathlib import Path

from decopy.licensing import licenses

_LICENSES_DIR = Path("tests/testdata/licenses")


def _detect(spdx_id: str) -> list[str]:
    text = json.loads((_LICENSES_DIR / f"{spdx_id}.json").read_text())["licenseText"]
    return list(licenses.find_licenses(licenses.clean_comments(text)))


class TestFindLicensesDedup(unittest.TestCase):
    def test_community_spec_does_not_self_duplicate(self):
        """Community-Spec-1.0 is itself published under CC-BY-4.0.

        Its text fires both the CC-BY text matcher and the embedded
        SPDX-License-Identifier tag, so CC-BY-4 came back twice alongside
        Community-Spec-1. The result must list each name once.
        """
        result = _detect("Community-Spec-1.0")
        self.assertEqual(len(result), len(set(result)), msg=f"duplicates in {result}")
        self.assertEqual(sorted(result), ["CC-BY-4", "Community-Spec-1"])


if __name__ == "__main__":
    unittest.main()
