package inbox

import (
	"fmt"

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

	"github.com/spf13/cobra"
)

type showOptions struct {
	threadID string
	markRead bool
}

func newShowCmd(root *rootOptions) *cobra.Command {
	opts := &showOptions{}

	cmd := &cobra.Command{
		Use:   "show",
		Short: "Show one thread with message history",
		RunE: func(cmd *cobra.Command, args []string) error {
			ctx := cmd.Context()

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

			s := store.NewInboxStore(sqlDB)
			agent := root.agent
			if opts.markRead && agent == "" {
				return protocol.InvalidInput("agent is required when using --mark-read", nil)
			}

			detail, err := s.GetThreadForAgent(ctx, opts.threadID, agent, opts.markRead)
			if err != nil {
				return err
			}

			resp := protocol.Success{
				OK:      true,
				Command: "show",
				Data: map[string]any{
					"thread":   detail.Thread,
					"messages": detail.Messages,
				},
			}

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

			if _, err := fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\t%s\n", detail.Thread.ThreadID, detail.Thread.Status, detail.Thread.Subject); err != nil {
				return err
			}
			for _, message := range detail.Messages {
				if _, err := fmt.Fprintf(cmd.OutOrStdout(), "- %s\t%s\t%s\n", message.MessageID, message.Kind, message.Summary); err != nil {
					return err
				}
				for _, artifact := range message.Artifacts {
					if _, err := fmt.Fprintf(cmd.OutOrStdout(), "  artifact\t%s\t%s\n", artifact.Kind, artifact.Path); err != nil {
						return err
					}
				}
			}
			return nil
		},
	}

	cmd.Flags().StringVar(&opts.threadID, "thread", "", "Thread ID")
	cmd.Flags().BoolVar(&opts.markRead, "mark-read", false, "Advance the caller's read cursor to the latest message")
	_ = cmd.MarkFlagRequired("thread")

	return cmd
}
