package orch

import (
	"fmt"

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

	"github.com/spf13/cobra"
)

type blockedOptions struct {
	runID string
}

func newBlockedCmd(root *rootOptions) *cobra.Command {
	opts := &blockedOptions{}

	cmd := &cobra.Command{
		Use:   "blocked",
		Short: "List blocked tasks and their latest question",
		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()

			blocked, err := store.NewOrchStore(sqlDB).ListBlockedTasks(ctx, opts.runID)
			if err != nil {
				return err
			}

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

			if len(blocked) == 0 {
				_, err = fmt.Fprintln(cmd.OutOrStdout(), "no blocked tasks")
				return err
			}
			for _, item := range blocked {
				if _, err := fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\n", item.Task.TaskID, item.Question.Summary); err != nil {
					return err
				}
			}
			return nil
		},
	}

	cmd.Flags().StringVar(&opts.runID, "run", "", "Run ID")
	_ = cmd.MarkFlagRequired("run")

	return cmd
}
