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

"""Debusine command line interface, workflow management commands."""

import argparse
from typing import override

from debusine.client.commands.base import (
    RequiredInputDataCommand,
    WorkspaceCommand,
)
from debusine.client.commands.work_requests import WorkRequestModelCommand
from debusine.client.models import CreateWorkflowRequest


class Start(
    RequiredInputDataCommand,
    WorkspaceCommand,
    WorkRequestModelCommand,
    group="workflow",
):
    """Start a workflow."""

    @override
    @classmethod
    def configure(cls, parser: argparse.ArgumentParser) -> None:
        super().configure(parser)
        parser.add_argument(
            "name",
            type=str,
            help=(
                "Name of the workflow template (or task, with --no-template)"
                " used to instantiate the workflow"
            ),
        )
        parser.add_argument(
            "--no-template",
            action="store_false",
            dest="use_template",
            default=True,
            help=(
                "Start a workflow directly without a template"
                " (only allowed for workspace owners)"
            ),
        )

    @override
    def run(self) -> None:
        if self.args.use_template:
            workflow = CreateWorkflowRequest(
                template_name=self.args.name,
                workspace=self.workspace,
                task_data=self.input_data,
            )
        else:
            workflow = CreateWorkflowRequest(
                task_name=self.args.name,
                workspace=self.workspace,
                task_data=self.input_data,
            )

        with self._api_call_or_fail():
            workflow_created = self.debusine.workflow_create(workflow)

        self.feedback("Workflow started:")
        self.show(workflow_created)


class LegacyStart(
    Start, name="create-workflow", deprecated="see `workflow start`"
):
    """Create a workflow from a template."""
