package orch

import (
	"fmt"
	"time"

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

	"github.com/spf13/cobra"
)

type councilWaitOptions struct {
	runID          string
	timeoutSeconds int
}

func newCouncilWaitCmd(root *rootOptions) *cobra.Command {
	opts := &councilWaitOptions{}

	cmd := &cobra.Command{
		Use:   "wait",
		Short: "Block until all council reviewers complete or timeout is reached",
		RunE: func(cmd *cobra.Command, args []string) error {
			ctx := cmd.Context()

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

			result, err := store.NewOrchStore(sqlDB).WaitForCouncil(ctx, store.CouncilWaitInput{
				RunID:   opts.runID,
				Timeout: time.Duration(opts.timeoutSeconds) * time.Second,
			})
			if err != nil {
				return err
			}

			resp := protocol.Success{
				OK:      true,
				Command: "council wait",
				Data: map[string]any{
					"run_id":       result.RunID,
					"woke":         result.Woke,
					"all_complete": result.AllComplete,
					"reviewers":    result.ReviewerStatuses,
				},
			}
			if root.json {
				return protocol.WriteJSON(cmd.OutOrStdout(), resp)
			}

			if !result.Woke {
				_, err = fmt.Fprintf(cmd.OutOrStdout(), "council wait timed out for run %s\n", result.RunID)
				return err
			}
			_, err = fmt.Fprintf(cmd.OutOrStdout(), "all council reviewers completed for run %s\n", result.RunID)
			return err
		},
	}

	cmd.Flags().StringVar(&opts.runID, "run", "", "Council run ID")
	cmd.Flags().IntVar(&opts.timeoutSeconds, "timeout-seconds", 0, "Maximum time to wait before timing out")
	_ = cmd.MarkFlagRequired("run")

	return cmd
}
