package orch

import (
	"fmt"

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

	"github.com/spf13/cobra"
)

type answerOptions struct {
	runID       string
	taskID      string
	body        string
	bodyFile    string
	payloadJSON string
}

func newAnswerCmd(root *rootOptions) *cobra.Command {
	opts := &answerOptions{}

	cmd := &cobra.Command{
		Use:   "answer",
		Short: "Answer the active blocked question for a task",
		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).AnswerTask(ctx, store.AnswerInput{
				RunID:       opts.runID,
				TaskID:      opts.taskID,
				Body:        body,
				PayloadJSON: opts.payloadJSON,
			})
			if err != nil {
				return err
			}

			resp := protocol.Success{
				OK:      true,
				Command: "answer",
				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(), "answered task %s on thread %s\n", result.Task.TaskID, result.Thread.ThreadID)
			return err
		},
	}

	cmd.Flags().StringVar(&opts.runID, "run", "", "Run ID")
	cmd.Flags().StringVar(&opts.taskID, "task", "", "Task ID")
	cmd.Flags().StringVar(&opts.body, "body", "", "Answer body")
	cmd.Flags().StringVar(&opts.bodyFile, "body-file", "", "Read answer body from file")
	cmd.Flags().StringVar(&opts.payloadJSON, "payload-json", "", "Structured payload JSON string")
	_ = cmd.MarkFlagRequired("run")
	_ = cmd.MarkFlagRequired("task")

	return cmd
}
