import json
from itertools import islice
from typing import List, Optional

import click

from ..client import HLJSONEncoder, WorkflowType, iter_workflows
from ..core import GQLBaseModel


@click.group("workflow")
@click.pass_context
def workflow_group(ctx):
    pass


@workflow_group.command("list")
@click.option(
    "--format",
    type=click.Choice(["table", "json"]),
    default="table",
    show_default=True,
    help="Output format",
)
@click.option("--limit", type=int, default=None, help="Maximum number of workflows to return")
@click.pass_context
def list_workflow_command(ctx, format, limit):
    """List workflows from cloud."""
    client = ctx.obj["client"]
    workflows_iter = iter_workflows(client)
    workflows = list(workflows_iter) if limit is None else list(islice(workflows_iter, limit))

    if format == "json":
        click.echo(
            json.dumps(
                [workflow.model_dump(mode="json") for workflow in workflows], indent=2, cls=HLJSONEncoder
            )
        )
        return

    if not workflows:
        click.echo("No workflows found.")
        return

    click.echo(f"Workflows from cloud ({len(workflows)} total):")
    click.echo()
    for i, workflow in enumerate(workflows, 1):
        click.echo(f"{i}. {workflow.name}")
        click.echo(f"   ID: {workflow.id}")
        click.echo()


@workflow_group.command("delete")
@click.option("-i", "--id", type=str, required=True, help="The ID of the workflow to delete")
@click.option("-y", "--yes", is_flag=True, help="Skip confirmation prompt")
@click.pass_context
def delete(ctx, id, yes):
    """Delete a workflow"""
    if not yes:
        if not click.confirm(f"Are you sure you want to delete workflow {id}?"):
            click.echo("Aborted.")
            return
    client = ctx.obj["client"]

    class DeleteWorkflowPayload(GQLBaseModel):
        errors: List[str]
        workflow: Optional[WorkflowType] = None

    result = client.deleteWorkflow(return_type=DeleteWorkflowPayload, id=id).gql_dict()
    click.echo(json.dumps(result, cls=HLJSONEncoder))
