# Copyright © The Debusine Developers
# See the AUTHORS file at the top-level directory of this distribution
#
# This file is part of Debusine. It is subject to the license terms
# in the LICENSE file found in the top-level directory of this
# distribution. No part of Debusine, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the LICENSE file.

"""Unit tests for the piuparts workflow."""
from typing import Any

from debusine.db.context import context
from debusine.db.models import WorkRequest
from debusine.server.workflows.piuparts import PiupartsWorkflow
from debusine.tasks.models import TaskTypes
from debusine.test.django import TestCase
from debusine.test.utils import preserve_task_registry


class PiupartsWorkflowTests(TestCase):
    """Unit tests for :py:class:`PiupartsWorkflow`."""

    def create_piuparts_workflow(
        self,
        *,
        extra_task_data: dict[str, Any],
    ) -> PiupartsWorkflow:
        """Create a piuparts workflow."""
        task_data = {
            "binary_artifacts": [39, 46, 53],
            "vendor": "debian",
            "codename": "bookworm",
        }
        task_data.update(extra_task_data)
        wr = self.playground.create_workflow(
            task_name="piuparts", task_data=task_data
        )
        return PiupartsWorkflow(wr)

    @preserve_task_registry()
    def test_populate(self) -> None:
        """Test populate."""
        with context.disable_permission_checks():
            # Expected architectures as per intersection of architectures
            # of binary_artifacts and requested architectures
            binaries_all = (
                self.playground.create_minimal_binary_packages_artifact(
                    "hello", "1.0.0", "1.0.0", "all"
                )
            )
            binaries_amd64 = (
                self.playground.create_minimal_binary_packages_artifact(
                    "hello", "1.0.0", "1.0.0", "amd64"
                )
            )
            binaries_i386 = (
                self.playground.create_minimal_binary_packages_artifact(
                    "hello", "1.0.0", "1.0.0", "i386"
                )
            )

            o = self.playground.create_workflow(
                task_name="piuparts",
                task_data={
                    "binary_artifacts": [
                        binaries_all.id,
                        binaries_amd64.id,
                        binaries_i386.id,
                    ],
                    "vendor": "debian",
                    "codename": "bookworm",
                    "extra_repositories": [
                        {
                            "url": "http://example.com/",
                            "suite": "bookworm",
                            "components": ["main"],
                        }
                    ],
                },
            )
        PiupartsWorkflow(o).populate()

        piuparts_wrs = WorkRequest.objects.filter(
            task_type=TaskTypes.WORKER,
            task_name="piuparts",
            parent=o,
        )
        self.assertEqual(piuparts_wrs.count(), 2)

        piuparts_wr = piuparts_wrs.get(
            task_data__input__binary_artifacts__contains=(
                f"{binaries_amd64.id}@artifacts",
            )
        )
        self.assertEqual(
            piuparts_wr.task_data,
            {
                "backend": "auto",
                "input": {
                    "binary_artifacts": [
                        f"{binaries_all.id}@artifacts",
                        f"{binaries_amd64.id}@artifacts",
                    ]
                },
                "host_architecture": "amd64",
                "base_tgz": "debian/match:codename=bookworm",
                "environment": "debian/match:codename=bookworm",
                "extra_repositories": [
                    {
                        "url": "http://example.com/",
                        "suite": "bookworm",
                        "components": ["main"],
                    }
                ],
            },
        )

        self.assertEqual(piuparts_wr.event_reactions_json, {})

        piuparts_wr = piuparts_wrs.get(
            task_data__input__binary_artifacts__contains=(
                f"{binaries_i386.id}@artifacts",
            )
        )
        self.assertEqual(
            piuparts_wr.task_data,
            {
                "backend": "auto",
                "input": {
                    "binary_artifacts": [
                        f"{binaries_all.id}@artifacts",
                        f"{binaries_i386.id}@artifacts",
                    ]
                },
                "host_architecture": "i386",
                "base_tgz": "debian/match:codename=bookworm",
                "environment": "debian/match:codename=bookworm",
                "extra_repositories": [
                    {
                        "url": "http://example.com/",
                        "suite": "bookworm",
                        "components": ["main"],
                    }
                ],
            },
        )

        self.assertEqual(piuparts_wr.event_reactions_json, {})

        # If only Architecture: all binary packages are provided
        # in binary_artifacts, then piuparts will be run once for
        # arch-all on {arch_all_host_architecture}.
        o = self.playground.create_workflow(
            task_name="piuparts",
            task_data={
                "binary_artifacts": [
                    binaries_all.id,
                    binaries_amd64.id,
                    binaries_i386.id,
                ],
                "vendor": "debian",
                "codename": "bookworm",
                "architectures": ["all"],
            },
        )
        PiupartsWorkflow(o).populate()

        piuparts_wrs = WorkRequest.objects.filter(
            task_type=TaskTypes.WORKER,
            task_name="piuparts",
            parent=o,
        )

        self.assertEqual(piuparts_wrs.count(), 1)

        piuparts_wr = piuparts_wrs.get(
            task_data__input__binary_artifacts__contains=(
                f"{binaries_all.id}@artifacts",
            )
        )
        self.assertEqual(
            piuparts_wr.task_data,
            {
                "backend": "auto",
                "input": {
                    "binary_artifacts": [
                        f"{binaries_all.id}@artifacts",
                    ]
                },
                "host_architecture": "amd64",
                "base_tgz": "debian/match:codename=bookworm",
                "environment": "debian/match:codename=bookworm",
                "extra_repositories": None,
            },
        )

    @context.disable_permission_checks()
    def test_get_label(self) -> None:
        """Test get_label()."""
        w = self.create_piuparts_workflow(extra_task_data={})
        self.assertEqual(w.get_label(), "run piuparts")
