package orch

import (
	"fmt"

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

	"github.com/spf13/cobra"
)

type councilTallyOptions struct {
	runID      string
	similarity string
}

func newCouncilTallyCmd(root *rootOptions) *cobra.Command {
	opts := &councilTallyOptions{}

	cmd := &cobra.Command{
		Use:   "tally",
		Short: "Group reviewer findings and compute council support counts",
		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).TallyCouncil(ctx, store.CouncilTallyInput{
				RunID:      opts.runID,
				Similarity: opts.similarity,
			})
			if err != nil {
				return err
			}

			resp := protocol.Success{
				OK:      true,
				Command: "council tally",
				Data: map[string]any{
					"run_id":                  result.RunID,
					"similarity":              result.Similarity,
					"counts":                  result.Counts,
					"grouped_recommendations": result.GroupedRecommendations,
				},
			}
			if root.json {
				return protocol.WriteJSON(cmd.OutOrStdout(), resp)
			}

			_, err = fmt.Fprintf(cmd.OutOrStdout(), "tallied council run %s into %d groups\n", result.RunID, len(result.GroupedRecommendations))
			return err
		},
	}

	cmd.Flags().StringVar(&opts.runID, "run", "", "Council run ID")
	cmd.Flags().StringVar(&opts.similarity, "similarity", "normal", "Grouping mode: strict or normal")
	_ = cmd.MarkFlagRequired("run")

	return cmd
}
