package inbox

import (
	"fmt"
	"time"

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

	"github.com/spf13/cobra"
)

type watchOptions struct {
	agent          string
	statuses       string
	timeoutSeconds int
	afterEventID   int64
}

func newWatchCmd(root *rootOptions) *cobra.Command {
	opts := &watchOptions{}

	cmd := &cobra.Command{
		Use:   "watch",
		Short: "Block until new matching activity appears",
		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)
			result, err := s.WatchThreads(ctx, store.WatchInput{
				Agent:        agent,
				Statuses:     parseCSV(opts.statuses),
				AfterEventID: opts.afterEventID,
				StartFromNow: !cmd.Flags().Changed("after-event"),
				Timeout:      time.Duration(opts.timeoutSeconds) * time.Second,
			})
			if err != nil {
				return err
			}
			if !result.Woke {
				return protocol.NoMatchingWork("no matching work before watch timeout")
			}

			data := map[string]any{
				"woke":          result.Woke,
				"next_event_id": result.NextEventID,
			}
			if result.Thread != nil {
				data["thread"] = result.Thread
			}
			if result.Message != nil {
				data["message"] = result.Message
			}
			if result.Event != nil {
				data["event"] = result.Event
			}

			resp := protocol.Success{
				OK:      true,
				Command: "watch",
				Data:    data,
			}

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

			_, err = fmt.Fprintf(cmd.OutOrStdout(), "watch woke on thread %s at event %d\n", result.Thread.ThreadID, result.NextEventID)
			return err
		},
	}

	cmd.Flags().StringVar(&opts.agent, "agent", "", "Assigned agent filter")
	cmd.Flags().StringVar(&opts.statuses, "status", "pending,blocked,done,failed", "Comma-separated status filter")
	cmd.Flags().IntVar(&opts.timeoutSeconds, "timeout-seconds", 0, "Maximum time to wait; 0 waits forever")
	cmd.Flags().Int64Var(&opts.afterEventID, "after-event", 0, "Resume after a known event ID")

	return cmd
}
