# Copyright 2024 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.

"""The collection manager for debian:package-build-logs collections."""

from typing import Any

from django.db import IntegrityError
from django.utils import timezone

from debusine.artifacts.models import (
    ArtifactCategory,
    BareDataCategory,
    CollectionCategory,
)
from debusine.db.models import Artifact, CollectionItem, User, WorkRequest
from debusine.server.collections.base import (
    CollectionManagerInterface,
    ItemAdditionError,
)


class DebianPackageBuildLogsManager(CollectionManagerInterface):
    """Manage collection of category debian:package-build-logs."""

    COLLECTION_CATEGORY = CollectionCategory.PACKAGE_BUILD_LOGS
    VALID_BARE_DATA_CATEGORIES = frozenset({BareDataCategory.PACKAGE_BUILD_LOG})
    VALID_ARTIFACT_CATEGORIES = frozenset({ArtifactCategory.PACKAGE_BUILD_LOG})

    def do_add_bare_data(
        self,
        category: BareDataCategory,
        *,
        user: User,
        workflow: WorkRequest | None = None,
        data: dict[str, Any] | None = None,
        name: str | None = None,  # noqa: U100
        replace: bool = False,
    ) -> CollectionItem:
        """Add bare data into the managed collection."""
        if data is None:
            raise ItemAdditionError(
                f"Adding to {CollectionCategory.PACKAGE_BUILD_LOGS} requires "
                f"data"
            )

        work_request_id = data["work_request_id"]
        vendor = data["vendor"]
        codename = data["codename"]
        architecture = data["architecture"]
        srcpkg_name = data["srcpkg_name"]
        srcpkg_version = data["srcpkg_version"]

        name_elements = [
            vendor,
            codename,
            architecture,
            srcpkg_name,
            srcpkg_version,
            str(work_request_id),
        ]
        name = "_".join(name_elements)

        if replace:
            self.remove_bare_data(name, user=user, workflow=workflow)

        try:
            return CollectionItem.objects.create_from_bare_data(
                category,
                parent_collection=self.collection,
                name=name,
                data=data,
                created_by_user=user,
                created_by_workflow=workflow,
            )
        except IntegrityError as exc:
            raise ItemAdditionError(str(exc))

    def do_remove_bare_data(
        self,
        name: str,
        *,
        user: User | None = None,
        workflow: WorkRequest | None = None,
    ) -> None:
        """Remove a bare data item from the collection."""
        CollectionItem.active_objects.filter(
            name=name,
            child_type=CollectionItem.Types.BARE,
            parent_collection=self.collection,
        ).update(
            removed_by_user=user,
            removed_by_workflow=workflow,
            removed_at=timezone.now(),
        )

    def do_add_artifact(
        self,
        artifact: Artifact,
        *,
        user: User,
        workflow: WorkRequest | None = None,
        variables: dict[str, Any] | None = None,
        name: str | None = None,  # noqa: U100
        replace: bool = False,
    ) -> CollectionItem:
        """Add bare data into the managed collection."""
        if variables is None:
            raise ItemAdditionError(
                f"Adding to {CollectionCategory.PACKAGE_BUILD_LOGS} requires "
                f"variables"
            )
        artifact_data = artifact.data

        work_request_id = variables["work_request_id"]
        vendor = variables["vendor"]
        codename = variables["codename"]
        architecture = variables["architecture"]
        if "srcpkg_name" in variables:
            srcpkg_name = variables["srcpkg_name"]
        else:
            srcpkg_name = artifact_data["source"]
        if "srcpkg_version" in variables:
            srcpkg_version = variables["srcpkg_version"]
        else:
            srcpkg_version = artifact_data["version"]

        data = {
            "work_request_id": work_request_id,
            "vendor": vendor,
            "codename": codename,
            "architecture": architecture,
            "srcpkg_name": srcpkg_name,
            "srcpkg_version": srcpkg_version,
        }
        work_request = WorkRequest.objects.get(id=work_request_id)
        if work_request.worker is not None:
            data["worker"] = work_request.worker.name

        name_elements = [
            vendor,
            codename,
            architecture,
            srcpkg_name,
            srcpkg_version,
            str(work_request_id),
        ]
        name = "_".join(name_elements)

        if replace:
            self.do_remove_child_types(
                [CollectionItem.Types.BARE, CollectionItem.Types.ARTIFACT],
                name=name,
                user=user,
                workflow=workflow,
            )

        try:
            return CollectionItem.objects.create_from_artifact(
                artifact,
                parent_collection=self.collection,
                name=name,
                data=data,
                created_by_user=user,
                created_by_workflow=workflow,
            )
        except IntegrityError as exc:
            raise ItemAdditionError(str(exc))

    def do_remove_artifact(
        self,
        artifact: Artifact,
        *,
        user: User | None = None,
        workflow: WorkRequest | None = None,
    ) -> None:
        """Remove the artifact from the collection."""
        CollectionItem.objects.filter(
            artifact=artifact, parent_collection=self.collection
        ).update(
            removed_by_user=user,
            removed_by_workflow=workflow,
            removed_at=timezone.now(),
        )
