package orch

import (
	"fmt"

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

	"github.com/spf13/cobra"
)

type retryOptions struct {
	runID    string
	taskID   string
	toAgent  string
	body     string
	bodyFile string
}

func newRetryCmd(root *rootOptions) *cobra.Command {
	opts := &retryOptions{}

	cmd := &cobra.Command{
		Use:   "retry",
		Short: "Retry a failed task by creating a new attempt",
		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()

			s := store.NewOrchStore(sqlDB)
			task, attempt, err := s.GetTaskWithLatestAttempt(ctx, opts.runID, opts.taskID)
			if err != nil {
				return err
			}

			result, err := s.RetryTask(ctx, store.RetryInput{
				RunID:            opts.runID,
				TaskID:           opts.taskID,
				ToAgent:          opts.toAgent,
				Body:             body,
				PrepareWorkspace: newAttemptReuseWorkspacePreparer(cmd, task, attempt),
			})
			if err != nil {
				return err
			}

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

			_, err = fmt.Fprintf(cmd.OutOrStdout(), "retried task %s as attempt %d\n", result.Task.TaskID, result.Attempt.AttemptNo)
			return err
		},
	}

	cmd.Flags().StringVar(&opts.runID, "run", "", "Run ID")
	cmd.Flags().StringVar(&opts.taskID, "task", "", "Task ID")
	cmd.Flags().StringVar(&opts.toAgent, "to", "", "Optional worker agent override")
	cmd.Flags().StringVar(&opts.body, "body", "", "Retry instruction body")
	cmd.Flags().StringVar(&opts.bodyFile, "body-file", "", "Read retry instruction body from file")
	_ = cmd.MarkFlagRequired("run")
	_ = cmd.MarkFlagRequired("task")

	return cmd
}
