package orch

import (
	"fmt"

	"ai-workflow-skill/internal/protocol"
	"ai-workflow-skill/internal/store"

	"github.com/spf13/cobra"
)

type cancelOptions struct {
	runID  string
	taskID string
	reason string
}

func newCancelCmd(root *rootOptions) *cobra.Command {
	opts := &cancelOptions{}

	cmd := &cobra.Command{
		Use:   "cancel",
		Short: "Cancel a task or an entire run",
		RunE: func(cmd *cobra.Command, args []string) error {
			ctx := cmd.Context()

			sqlDB, err := openOrchDB(ctx, root.dbPath)
			if err != nil {
				return err
			}
			defer sqlDB.Close()

			result, err := store.NewOrchStore(sqlDB).Cancel(ctx, store.CancelControlInput{
				RunID:  opts.runID,
				TaskID: opts.taskID,
				Reason: opts.reason,
			})
			if err != nil {
				return err
			}

			resp := protocol.Success{
				OK:      true,
				Command: "cancel",
				Data: map[string]any{
					"run":             result.Run,
					"cancelled_tasks": result.CancelledTasks,
				},
			}
			if root.json {
				return protocol.WriteJSON(cmd.OutOrStdout(), resp)
			}

			if opts.taskID != "" {
				_, err = fmt.Fprintf(cmd.OutOrStdout(), "cancelled task %s in run %s\n", opts.taskID, opts.runID)
				return err
			}
			_, err = fmt.Fprintf(cmd.OutOrStdout(), "cancelled run %s (%d tasks)\n", opts.runID, len(result.CancelledTasks))
			return err
		},
	}

	cmd.Flags().StringVar(&opts.runID, "run", "", "Run ID")
	cmd.Flags().StringVar(&opts.taskID, "task", "", "Optional task ID")
	cmd.Flags().StringVar(&opts.reason, "reason", "", "Cancellation reason")
	_ = cmd.MarkFlagRequired("run")

	return cmd
}
