package inbox

import (
	"fmt"

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

	"github.com/spf13/cobra"
)

type sendOptions struct {
	from        string
	to          string
	threadID    string
	runID       string
	taskID      string
	subject     string
	kind        string
	summary     string
	body        string
	bodyFile    string
	payloadJSON string
	priority    string
	artifacts   artifactOptions
}

func newSendCmd(root *rootOptions) *cobra.Command {
	opts := &sendOptions{}

	cmd := &cobra.Command{
		Use:   "send",
		Short: "Create a thread with an initial directed message",
		RunE: func(cmd *cobra.Command, args []string) error {
			ctx := cmd.Context()

			from := opts.from
			if from == "" {
				from = root.agent
			}
			if from == "" {
				return protocol.InvalidInput("from agent is required", nil)
			}
			if opts.threadID == "" && opts.subject == "" {
				return protocol.InvalidInput("subject is required when creating a new thread", nil)
			}

			body, err := resolveBodyValue(opts.body, opts.bodyFile)
			if err != nil {
				return err
			}
			artifacts, err := resolveArtifacts(opts.artifacts)
			if err != nil {
				return err
			}

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

			s := store.NewInboxStore(sqlDB)
			thread, message, err := s.Send(ctx, store.SendInput{
				ThreadID:    opts.threadID,
				RunID:       opts.runID,
				TaskID:      opts.taskID,
				Subject:     opts.subject,
				FromAgent:   from,
				ToAgent:     opts.to,
				Kind:        opts.kind,
				Summary:     opts.summary,
				Body:        body,
				PayloadJSON: opts.payloadJSON,
				Priority:    opts.priority,
				Artifacts:   artifacts,
			})
			if err != nil {
				return err
			}

			resp := protocol.Success{
				OK:      true,
				Command: "send",
				Data: map[string]any{
					"thread":  thread,
					"message": message,
				},
			}

			if root.json {
				return protocol.WriteJSON(cmd.OutOrStdout(), resp)
			}

			_, err = fmt.Fprintf(cmd.OutOrStdout(), "created thread %s\n", thread.ThreadID)
			return err
		},
	}

	cmd.Flags().StringVar(&opts.from, "from", "", "Sending agent")
	cmd.Flags().StringVar(&opts.to, "to", "", "Receiving agent")
	cmd.Flags().StringVar(&opts.threadID, "thread", "", "Optional thread ID override")
	cmd.Flags().StringVar(&opts.runID, "run", "", "Optional run ID override")
	cmd.Flags().StringVar(&opts.taskID, "task", "", "Optional task ID override")
	cmd.Flags().StringVar(&opts.subject, "subject", "", "Thread subject")
	cmd.Flags().StringVar(&opts.kind, "kind", "task", "Initial message kind")
	cmd.Flags().StringVar(&opts.summary, "summary", "", "Short message summary")
	cmd.Flags().StringVar(&opts.body, "body", "", "Message body")
	cmd.Flags().StringVar(&opts.bodyFile, "body-file", "", "Read message body from file")
	cmd.Flags().StringVar(&opts.payloadJSON, "payload-json", "", "Structured payload JSON string")
	cmd.Flags().StringVar(&opts.priority, "priority", "normal", "Thread priority")
	addArtifactFlags(cmd, &opts.artifacts)

	_ = cmd.MarkFlagRequired("to")

	return cmd
}
