package orch

import (
	"fmt"

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

	"github.com/spf13/cobra"
)

type runInitOptions struct {
	runID   string
	goal    string
	summary string
}

type runShowOptions struct {
	runID string
}

func newRunCmd(root *rootOptions) *cobra.Command {
	cmd := &cobra.Command{
		Use:   "run",
		Short: "Run management commands",
	}

	cmd.AddCommand(newRunInitCmd(root))
	cmd.AddCommand(newRunShowCmd(root))

	return cmd
}

func newRunInitCmd(root *rootOptions) *cobra.Command {
	opts := &runInitOptions{}

	cmd := &cobra.Command{
		Use:   "init",
		Short: "Create a new orchestration 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()

			run, err := store.NewOrchStore(sqlDB).CreateRun(ctx, store.CreateRunInput{
				RunID:   opts.runID,
				Goal:    opts.goal,
				Summary: opts.summary,
			})
			if err != nil {
				return err
			}

			resp := protocol.Success{
				OK:      true,
				Command: "run init",
				Data: map[string]any{
					"run": run,
				},
			}
			if root.json {
				return protocol.WriteJSON(cmd.OutOrStdout(), resp)
			}

			_, err = fmt.Fprintf(cmd.OutOrStdout(), "created run %s\n", run.RunID)
			return err
		},
	}

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

	return cmd
}

func newRunShowCmd(root *rootOptions) *cobra.Command {
	opts := &runShowOptions{}

	cmd := &cobra.Command{
		Use:   "show",
		Short: "Show run metadata and aggregate 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()

			overview, err := store.NewOrchStore(sqlDB).GetRunOverview(ctx, opts.runID)
			if err != nil {
				return err
			}

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

			_, err = fmt.Fprintf(cmd.OutOrStdout(), "run %s status %s\n", overview.Run.RunID, overview.Run.Status)
			return err
		},
	}

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

	return cmd
}
