"""Cancel command - Cancel a running task."""

import click

from flow import Flow
from flow.errors import AuthenticationError

from .base import BaseCommand, console


class CancelCommand(BaseCommand):
    """Cancel a running task."""

    @property
    def name(self) -> str:
        return "cancel"

    @property
    def help(self) -> str:
        return "Cancel a running task"

    def get_command(self) -> click.Command:
        @click.command(name=self.name, help=self.help)
        @click.argument("task_id")
        @click.option("--yes", "-y", is_flag=True, help="Skip confirmation prompt")
        def cancel(task_id: str, yes: bool):
            """Cancel a running task.

            TASK_ID: The task ID to cancel

            \b
            Examples:
                flow cancel task_123456
                flow cancel task_123456 --yes  # Skip confirmation
            """
            self._execute(task_id, yes)

        return cancel

    def _execute(self, task_id: str, yes: bool) -> None:
        """Execute the cancel command."""
        try:
            flow_client = Flow()

            # Get current status
            status = flow_client.status(task_id)

            if status.state not in ["pending", "preparing", "running"]:
                console.print(f"Task {task_id} is already {status.state}")
                return

            # Confirm cancellation
            if not yes:
                confirm = click.confirm(f"Cancel task {task_id}?")
                if not confirm:
                    console.print("Cancelled")
                    return

            # Cancel the task
            flow_client.cancel(task_id)
            console.print(f"[green]✓[/green] Task {task_id} cancelled")

        except AuthenticationError:
            self.handle_auth_error()
        except Exception as e:
            self.handle_error(str(e))


# Export command instance
command = CancelCommand()
