package orch

import (
	"fmt"

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

	"github.com/spf13/cobra"
)

type taskAddOptions struct {
	runID          string
	taskID         string
	title          string
	summary        string
	defaultTo      string
	acceptanceJSON string
	priority       string
}

func newTaskCmd(root *rootOptions) *cobra.Command {
	cmd := &cobra.Command{
		Use:   "task",
		Short: "Task management commands",
	}

	cmd.AddCommand(newTaskAddCmd(root))
	return cmd
}

func newTaskAddCmd(root *rootOptions) *cobra.Command {
	opts := &taskAddOptions{}

	cmd := &cobra.Command{
		Use:   "add",
		Short: "Add a task to a 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()

			task, err := store.NewOrchStore(sqlDB).AddTask(ctx, store.AddTaskInput{
				RunID:          opts.runID,
				TaskID:         opts.taskID,
				Title:          opts.title,
				Summary:        opts.summary,
				DefaultTo:      opts.defaultTo,
				AcceptanceJSON: opts.acceptanceJSON,
				Priority:       opts.priority,
			})
			if err != nil {
				return err
			}

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

			_, err = fmt.Fprintf(cmd.OutOrStdout(), "added task %s to run %s\n", task.TaskID, task.RunID)
			return err
		},
	}

	cmd.Flags().StringVar(&opts.runID, "run", "", "Run ID")
	cmd.Flags().StringVar(&opts.taskID, "task", "", "Task ID")
	cmd.Flags().StringVar(&opts.title, "title", "", "Task title")
	cmd.Flags().StringVar(&opts.summary, "summary", "", "Task summary")
	cmd.Flags().StringVar(&opts.defaultTo, "default-to", "", "Default worker agent")
	cmd.Flags().StringVar(&opts.acceptanceJSON, "acceptance-json", "", "Acceptance criteria JSON")
	cmd.Flags().StringVar(&opts.priority, "priority", "normal", "Task priority")
	_ = cmd.MarkFlagRequired("run")
	_ = cmd.MarkFlagRequired("task")
	_ = cmd.MarkFlagRequired("title")

	return cmd
}
