#!/usr/bin/env python3

# Unit tests for the GroupingStrategy abstraction.
# 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.

"""Unit tests for grouping_strategy.

These pin the strategy classes in isolation. They must agree with the
characterization tests in grouping_policy_test.py, which lock the equivalent
behaviour at the (still-live) call sites the strategies will replace.
"""

import unittest

from decopy import cmdoptions, core_types, nodes
from decopy.grouping_strategy import (
    CopyrightGrouping,
    GroupingStrategy,
    LicenseGrouping,
    grouping_strategy_for,
)


def _options(*, group_by="license", split_on_license=True, split_debian=True):
    flags = ["--no-progress", "--root", "tests/testdata/one", "--group-by", group_by]
    if not split_on_license:
        flags.append("--no-split-on-license")
    if not split_debian:
        flags.append("--no-split-debian")
    return cmdoptions.process_options(flags)


class FactoryTest(unittest.TestCase):
    def test_license_option_selects_license_grouping(self):
        strategy = grouping_strategy_for(_options(group_by="license"))
        self.assertIsInstance(strategy, LicenseGrouping)

    def test_copyright_option_selects_copyright_grouping(self):
        strategy = grouping_strategy_for(_options(group_by="copyright"))
        self.assertIsInstance(strategy, CopyrightGrouping)

    def test_strategies_are_shared_singletons(self):
        a = grouping_strategy_for(_options(group_by="license"))
        b = grouping_strategy_for(_options(group_by="license"))
        self.assertIs(a, b)


class KeyCopyrightSlotTest(unittest.TestCase):
    def test_license_drops_the_copyright_slot(self):
        self.assertIsNone(LicenseGrouping().key_copyright_slot(("alice@x",)))

    def test_copyright_keeps_the_copyright_slot(self):
        self.assertEqual(
            CopyrightGrouping().key_copyright_slot(("alice@x",)), ("alice@x",)
        )


class KeepsMisplacedTest(unittest.TestCase):
    def setUp(self):
        self.group_key = ("MIT", ("alice@x",), "")
        self.group_key_no_copyright = ("MIT", (), "")

    def test_license_keeps_only_on_exact_match(self):
        strategy = LicenseGrouping()
        self.assertTrue(
            strategy.keeps_misplaced(
                self.group_key, self.group_key, self.group_key_no_copyright
            )
        )
        self.assertFalse(
            strategy.keeps_misplaced(
                ("MIT", ("bob@x",), ""),
                self.group_key,
                self.group_key_no_copyright,
            )
        )

    def test_copyright_keeps_on_exact_match(self):
        strategy = CopyrightGrouping()
        self.assertTrue(
            strategy.keeps_misplaced(
                self.group_key, self.group_key, self.group_key_no_copyright
            )
        )

    def test_copyright_rescues_uncopyrighted_file(self):
        # An empty copyright slot matches the no-copyright key -> kept.
        strategy = CopyrightGrouping()
        self.assertTrue(
            strategy.keeps_misplaced(
                self.group_key_no_copyright,
                self.group_key,
                self.group_key_no_copyright,
            )
        )

    def test_copyright_drops_mismatched_nonempty_copyright(self):
        strategy = CopyrightGrouping()
        self.assertFalse(
            strategy.keeps_misplaced(
                ("MIT", ("bob@x",), ""),
                self.group_key,
                self.group_key_no_copyright,
            )
        )


class SplittingPathTest(unittest.TestCase):
    """The shared base-class splitting_path matches file_policy.splitting_path."""

    def setUp(self):
        self.strategy = LicenseGrouping()
        self.root = nodes.DirInfo(parent=None, name="")
        self.src = nodes.DirInfo(parent=self.root, name="src")
        self.root.file_list["src"] = self.src
        self.debian = nodes.DirInfo(parent=self.root, name="debian")
        self.root.file_list["debian"] = self.debian
        self.lic = nodes.DirInfo(parent=self.src, name="lic")
        self.lic.add_licenses(["MIT"])
        self.src.file_list["lic"] = self.lic

    def test_root_returns_its_own_name(self):
        self.assertEqual(self.strategy.splitting_path(self.root, _options()), "")

    def test_license_dir_with_split_on_license(self):
        opts = _options(split_on_license=True)
        self.assertEqual(self.strategy.splitting_path(self.lic, opts), "src/lic")

    def test_license_dir_recurses_without_split_on_license(self):
        opts = _options(split_on_license=False)
        self.assertEqual(self.strategy.splitting_path(self.lic, opts), "")

    def test_debian_dir_with_split_debian(self):
        opts = _options(split_debian=True)
        self.assertEqual(self.strategy.splitting_path(self.debian, opts), "debian")

    def test_debian_dir_recurses_without_split_debian(self):
        opts = _options(split_debian=False)
        self.assertEqual(self.strategy.splitting_path(self.debian, opts), "")

    def test_file_delegates_to_parent(self):
        f = nodes.FileInfo(parent=self.lic, name="a.txt")
        self.assertEqual(
            self.strategy.splitting_path(f, _options(split_on_license=True)),
            "src/lic",
        )

    def test_parentless_file_returns_none(self):
        orphan = nodes.FileInfo(parent=None, name="o.txt")
        self.assertIsNone(self.strategy.splitting_path(orphan, _options()))


class SortBandTest(unittest.TestCase):
    def setUp(self):
        self.strategy = LicenseGrouping()

    def test_normal_group_is_band_zero(self):
        band = self.strategy.sort_band("MIT", "src", _options(split_debian=True))
        self.assertEqual(band, 0)

    def test_debian_group_is_band_two_with_split_debian(self):
        band = self.strategy.sort_band("MIT", "debian", _options(split_debian=True))
        self.assertEqual(band, 2)

    def test_debian_group_is_band_zero_without_split_debian(self):
        band = self.strategy.sort_band("MIT", "debian", _options(split_debian=False))
        self.assertEqual(band, 0)

    def test_unknown_license_is_band_one(self):
        band = self.strategy.sort_band(
            core_types.UNKNOWN, "src", _options(split_debian=True)
        )
        self.assertEqual(band, 1)

    def test_unknown_overrides_debian_band(self):
        band = self.strategy.sort_band(
            core_types.UNKNOWN_COPYRIGHTED, "debian", _options(split_debian=True)
        )
        self.assertEqual(band, 1)


class AbstractContractTest(unittest.TestCase):
    def test_base_class_cannot_be_instantiated(self):
        with self.assertRaises(TypeError):
            GroupingStrategy()  # type: ignore[abstract]


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