package inbox

import (
	"fmt"
	"strings"

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

	"github.com/spf13/cobra"
)

type fetchOptions struct {
	agent    string
	statuses string
	limit    int
	unread   bool
}

func newFetchCmd(root *rootOptions) *cobra.Command {
	opts := &fetchOptions{}

	cmd := &cobra.Command{
		Use:   "fetch",
		Short: "List candidate threads for an agent",
		RunE: func(cmd *cobra.Command, args []string) error {
			ctx := cmd.Context()

			agent := opts.agent
			if agent == "" {
				agent = root.agent
			}

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

			s := store.NewInboxStore(sqlDB)
			threads, err := s.FetchThreads(ctx, store.FetchInput{
				Agent:    agent,
				Statuses: parseCSV(opts.statuses),
				Limit:    opts.limit,
				Unread:   opts.unread,
			})
			if err != nil {
				return err
			}
			if len(threads) == 0 {
				return protocol.NoMatchingWork("no matching work")
			}

			resp := protocol.Success{
				OK:      true,
				Command: "fetch",
				Data: map[string]any{
					"threads": threads,
				},
			}

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

			for _, thread := range threads {
				if _, err := fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\t%s\n", thread.ThreadID, thread.Status, thread.Subject); err != nil {
					return err
				}
			}
			return nil
		},
	}

	cmd.Flags().StringVar(&opts.agent, "agent", "", "Assigned agent filter")
	cmd.Flags().StringVar(&opts.statuses, "status", "pending", "Comma-separated status filter")
	cmd.Flags().IntVar(&opts.limit, "limit", 20, "Maximum number of threads")
	cmd.Flags().BoolVar(&opts.unread, "unread", false, "Only return threads whose latest message is unread by the agent")

	return cmd
}

func parseCSV(value string) []string {
	if strings.TrimSpace(value) == "" {
		return nil
	}

	raw := strings.Split(value, ",")
	out := make([]string, 0, len(raw))
	for _, entry := range raw {
		entry = strings.TrimSpace(entry)
		if entry != "" {
			out = append(out, entry)
		}
	}
	return out
}
