package orch

import (
	"fmt"

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

	"github.com/spf13/cobra"
)

type dispatchOptions struct {
	runID          string
	taskID         string
	toAgent        string
	body           string
	bodyFile       string
	baseRef        string
	repoPath       string
	workspaceRoot  string
	strictWorktree bool
}

func newDispatchCmd(root *rootOptions) *cobra.Command {
	opts := &dispatchOptions{}

	cmd := &cobra.Command{
		Use:   "dispatch",
		Short: "Dispatch a ready task to a worker through inbox",
		RunE: func(cmd *cobra.Command, args []string) error {
			body, err := resolveBodyValue(opts.body, opts.bodyFile)
			if err != nil {
				return err
			}

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

			result, err := store.NewOrchStore(sqlDB).DispatchTask(ctx, store.DispatchInput{
				RunID:            opts.runID,
				TaskID:           opts.taskID,
				ToAgent:          opts.toAgent,
				Body:             body,
				BaseRef:          opts.baseRef,
				PrepareWorkspace: newDispatchWorkspacePreparer(cmd, *opts),
			})
			if err != nil {
				return err
			}

			resp := protocol.Success{
				OK:      true,
				Command: "dispatch",
				Data: map[string]any{
					"task":    result.Task,
					"attempt": result.Attempt,
					"thread":  result.Thread,
					"message": result.Message,
				},
			}
			if root.json {
				return protocol.WriteJSON(cmd.OutOrStdout(), resp)
			}

			_, err = fmt.Fprintf(
				cmd.OutOrStdout(),
				"dispatched task %s to %s as thread %s\n",
				result.Task.TaskID,
				result.Attempt.AssignedTo,
				result.Attempt.ThreadID,
			)
			return err
		},
	}

	cmd.Flags().StringVar(&opts.runID, "run", "", "Run ID")
	cmd.Flags().StringVar(&opts.taskID, "task", "", "Task ID")
	cmd.Flags().StringVar(&opts.toAgent, "to", "", "Worker agent override")
	cmd.Flags().StringVar(&opts.body, "body", "", "Task message body")
	cmd.Flags().StringVar(&opts.bodyFile, "body-file", "", "Read task message body from file")
	cmd.Flags().StringVar(&opts.baseRef, "base-ref", "", "Optional base ref to record on the attempt")
	cmd.Flags().StringVar(&opts.repoPath, "repo-path", "", "Source repository path for worktree dispatch")
	cmd.Flags().StringVar(&opts.workspaceRoot, "workspace-root", "", "Workspace root for worktree dispatch")
	cmd.Flags().BoolVar(&opts.strictWorktree, "strict-worktree", false, "Require strict worktree setup")
	_ = cmd.MarkFlagRequired("run")
	_ = cmd.MarkFlagRequired("task")

	return cmd
}
