package orch

import (
	"fmt"

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

	"github.com/spf13/cobra"
)

type readyOptions struct {
	runID string
	limit int
}

func newReadyCmd(root *rootOptions) *cobra.Command {
	opts := &readyOptions{}

	cmd := &cobra.Command{
		Use:   "ready",
		Short: "List tasks that are ready for dispatch",
		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()

			tasks, err := store.NewOrchStore(sqlDB).ListReadyTasks(ctx, store.ListReadyInput{
				RunID: opts.runID,
				Limit: opts.limit,
			})
			if err != nil {
				return err
			}

			resp := protocol.Success{
				OK:      true,
				Command: "ready",
				Data: map[string]any{
					"tasks": tasks,
				},
			}
			if root.json {
				return protocol.WriteJSON(cmd.OutOrStdout(), resp)
			}

			if len(tasks) == 0 {
				_, err = fmt.Fprintln(cmd.OutOrStdout(), "no ready tasks")
				return err
			}
			for _, task := range tasks {
				if _, err := fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\t%s\n", task.TaskID, task.Priority, task.Title); err != nil {
					return err
				}
			}
			return nil
		},
	}

	cmd.Flags().StringVar(&opts.runID, "run", "", "Run ID")
	cmd.Flags().IntVar(&opts.limit, "limit", 20, "Maximum number of tasks to list")
	_ = cmd.MarkFlagRequired("run")

	return cmd
}
