package orch

import (
	"fmt"

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

	"github.com/spf13/cobra"
)

type depAddOptions struct {
	runID      string
	taskID     string
	dependsOn  string
}

func newDepCmd(root *rootOptions) *cobra.Command {
	cmd := &cobra.Command{
		Use:   "dep",
		Short: "Task dependency commands",
	}

	cmd.AddCommand(newDepAddCmd(root))
	return cmd
}

func newDepAddCmd(root *rootOptions) *cobra.Command {
	opts := &depAddOptions{}

	cmd := &cobra.Command{
		Use:   "add",
		Short: "Add a dependency edge to a task",
		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()

			dep, err := store.NewOrchStore(sqlDB).AddDependency(ctx, store.AddDependencyInput{
				RunID:           opts.runID,
				TaskID:          opts.taskID,
				DependsOnTaskID: opts.dependsOn,
			})
			if err != nil {
				return err
			}

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

			_, err = fmt.Fprintf(cmd.OutOrStdout(), "added dependency %s -> %s\n", dep.TaskID, dep.DependsOnTaskID)
			return err
		},
	}

	cmd.Flags().StringVar(&opts.runID, "run", "", "Run ID")
	cmd.Flags().StringVar(&opts.taskID, "task", "", "Task ID")
	cmd.Flags().StringVar(&opts.dependsOn, "depends-on", "", "Dependency task ID")
	_ = cmd.MarkFlagRequired("run")
	_ = cmd.MarkFlagRequired("task")
	_ = cmd.MarkFlagRequired("depends-on")

	return cmd
}
