package orch

import (
	"fmt"

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

	"github.com/spf13/cobra"
)

type reconcileOptions struct {
	runID string
}

func newReconcileCmd(root *rootOptions) *cobra.Command {
	opts := &reconcileOptions{}

	cmd := &cobra.Command{
		Use:   "reconcile",
		Short: "Reconcile inbox thread state back into orch task state",
		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).ReconcileRun(ctx, opts.runID)
			if err != nil {
				return err
			}

			resp := protocol.Success{
				OK:      true,
				Command: "reconcile",
				Data: map[string]any{
					"run":           result.Run,
					"task_counts":   result.TaskCounts,
					"updated_tasks": result.UpdatedTasks,
				},
			}
			if root.json {
				return protocol.WriteJSON(cmd.OutOrStdout(), resp)
			}

			_, err = fmt.Fprintf(cmd.OutOrStdout(), "reconciled run %s (%d updated tasks)\n", result.Run.RunID, len(result.UpdatedTasks))
			return err
		},
	}

	cmd.Flags().StringVar(&opts.runID, "run", "", "Run ID")
	_ = cmd.MarkFlagRequired("run")

	return cmd
}
