package orch

import (
	"fmt"

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

	"github.com/spf13/cobra"
)

type statusOptions struct {
	runID string
}

func newStatusCmd(root *rootOptions) *cobra.Command {
	opts := &statusOptions{}

	cmd := &cobra.Command{
		Use:   "status",
		Short: "Show task state summary for the 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()

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

			resp := protocol.Success{
				OK:      true,
				Command: "status",
				Data: map[string]any{
					"run":         overview.Run,
					"task_counts": overview.TaskCounts,
					"tasks":       overview.Tasks,
				},
			}
			if root.json {
				return protocol.WriteJSON(cmd.OutOrStdout(), resp)
			}

			if _, err := fmt.Fprintf(cmd.OutOrStdout(), "run %s status %s\n", overview.Run.RunID, overview.Run.Status); err != nil {
				return err
			}
			for _, task := range overview.Tasks {
				if _, err := fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\t%s\n", task.TaskID, task.Status, task.Title); err != nil {
					return err
				}
			}
			return nil
		},
	}

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

	return cmd
}
