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

"""View for DebianPipeline work request."""

from typing import Any, override

from debusine.artifacts.models import TaskTypes
from debusine.db.models import WorkRequest
from debusine.server.workflows import DebianPipelineWorkflow, QAWorkflow
from debusine.web.views.qa import QATab
from debusine.web.views.work_request import Tab, WorkRequestPlugin


class DebianPipelineViewWorkRequestPlugin(WorkRequestPlugin):
    """View for DebianPipeline work request."""

    task_type = TaskTypes.WORKFLOW
    task_name = "debian_pipeline"
    task: DebianPipelineWorkflow

    def __init__(self, work_request: WorkRequest) -> None:
        """Find the relevant workflow elements."""
        super().__init__(work_request)

        self.tab_qa: QATab | None = self.make_tab_qa()

    def make_tab_qa(self) -> QATab | None:
        """Instantiate a QA tab, if QA data exist."""
        # Find QA sub-workflow
        try:
            qa_workflow = self.work_request.children.get(
                task_type=TaskTypes.WORKFLOW,
                task_name="qa",
                task_data__update_qa_results=False,
            )
        except WorkRequest.DoesNotExist:
            return None

        qa_task = QAWorkflow(qa_workflow)

        tab = QATab(qa_workflow, qa_task)
        if not tab.has_data:
            return None

        return tab

    @override
    def is_enabled(self) -> bool:
        return self.tab_qa is not None

    @override
    def add_tabs(self, tabs: list[Tab]) -> None:
        if self.tab_qa is not None:
            tabs.insert(1, self.tab_qa)

    @override
    def get_context_data(self) -> dict[str, Any]:
        return {}
