package orch

import (
	"fmt"

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

	"github.com/spf13/cobra"
)

type councilStartOptions struct {
	runID         string
	target        string
	targetFile    string
	repoPath      string
	targetTaskID  string
	targetType    string
	mode          string
	outputMode    string
	onlyUnanimous bool
}

func newCouncilStartCmd(root *rootOptions) *cobra.Command {
	opts := &councilStartOptions{}

	cmd := &cobra.Command{
		Use:   "start",
		Short: "Create and dispatch a three-reviewer council run",
		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).StartCouncil(ctx, store.CouncilStartInput{
				RunID:         opts.runID,
				Target:        opts.target,
				TargetFile:    opts.targetFile,
				RepoPath:      opts.repoPath,
				TargetTaskID:  opts.targetTaskID,
				TargetType:    opts.targetType,
				Mode:          opts.mode,
				OutputMode:    opts.outputMode,
				OnlyUnanimous: opts.onlyUnanimous,
			})
			if err != nil {
				return err
			}

			resp := protocol.Success{
				OK:      true,
				Command: "council start",
				Data: map[string]any{
					"run_id":         result.Run.RunID,
					"mode":           result.Run.Mode,
					"target_type":    result.Run.TargetType,
					"output":         result.Run.OutputMode,
					"only_unanimous": result.Run.OnlyUnanimous,
					"target":         result.Input,
					"reviewers":      result.Reviewers,
				},
			}
			if root.json {
				return protocol.WriteJSON(cmd.OutOrStdout(), resp)
			}

			_, err = fmt.Fprintf(cmd.OutOrStdout(), "started council run %s with %d reviewers\n", result.Run.RunID, len(result.Reviewers))
			return err
		},
	}

	cmd.Flags().StringVar(&opts.runID, "run", "", "Run ID")
	cmd.Flags().StringVar(&opts.target, "target", "", "Inline target prompt")
	cmd.Flags().StringVar(&opts.targetFile, "target-file", "", "Optional target context file")
	cmd.Flags().StringVar(&opts.repoPath, "repo-path", "", "Optional repository path for review context")
	cmd.Flags().StringVar(&opts.targetTaskID, "task-id", "", "Optional related task ID")
	cmd.Flags().StringVar(&opts.targetType, "target-type", "mixed", "Target type: text, repo, or mixed")
	cmd.Flags().StringVar(&opts.mode, "mode", "brainstorm", "Council mode: brainstorm or review")
	cmd.Flags().StringVar(&opts.outputMode, "output", "both", "Output mode: markdown, json, or both")
	cmd.Flags().BoolVar(&opts.onlyUnanimous, "only-unanimous", false, "Show only unanimous recommendations in downstream report defaults")
	_ = cmd.MarkFlagRequired("run")

	return cmd
}
