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

"""End-to-end: a compound SPDX-License-Identifier tag yields per-atom stanzas.

A source file carrying `SPDX-License-Identifier: MIT or Apache-2.0` must produce
a Files paragraph whose License field is the canonicalised disjunction
(`Apache-2 or Expat`) and one standalone License stanza per atom, not a single
paragraph keyed by the whole expression string.
"""

import contextlib
import io
import unittest

from decopy import cmdoptions
from decopy.decopy import prepare_output_groups
from decopy.dep5doc import dep5, output
from decopy.dep5doc.renderer import renderer_for
from decopy.fstree import tree


def _generate(path: str) -> str:
    options = cmdoptions.process_options(["--no-progress", "--root", path])
    filetree = tree.RootInfo.build(options)
    copyright_ = dep5.read_copyright(options)
    copyright_.process(filetree)
    filetree.process(options)
    copyright_.remove_misplaced_files(options)
    groups = prepare_output_groups(filetree, copyright_, options)
    buf = io.StringIO()
    with contextlib.redirect_stdout(buf):
        output.generate_output(
            groups, filetree, copyright_, options, renderer_for(options)
        )
    return buf.getvalue()


class TestSpdxCompoundEndToEnd(unittest.TestCase):
    def test_compound_field_and_per_atom_stanzas(self):
        out = _generate("tests/testdata/spdxcompound")

        # Files paragraph: canonicalised disjunction, not the raw SPDX ids.
        self.assertIn("License: Apache-2 or Expat", out)
        self.assertNotIn("MIT or Apache-2.0", out)

        # The compound appears only once -- as the Files field, never as its own
        # standalone stanza.
        self.assertEqual(out.count("License: Apache-2 or Expat"), 1)

        # One standalone License stanza per atom (each on its own header line).
        self.assertIn("\nLicense: Apache-2\n", out)
        self.assertIn("\nLicense: Expat\n", out)


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