package job

import (
	"context"
	"fmt"

	"github.com/shiningrush/fastflow/pkg/mod"
	"github.com/spf13/cobra"
	"github.com/tidbcloud/metrics-integration/global/internal/domain/workflow/action"
	"github.com/tidbcloud/metrics-integration/global/internal/infrastructure/di"
)

func registerFastflowJobFunc(cmd *cobra.Command) {
	// Retry DAG instance command
	{
		var dagInsID string
		retryCmd := &cobra.Command{
			Use:   "retry-dag-ins",
			Short: "Retry a failed DAG instance",
			Long: `Retry a failed DAG instance by DAG instance ID.
			
This command retries a failed DAG instance in the fastflow workflow system.
It will restart the DAG instance from the failed point.`,
			Example: `  # Retry a DAG instance by ID
  job workflow retry-dag-ins --dag-ins-id "abc123"
  
  # Retry a DAG instance by name
  job workflow retry-dag-ins --dag-ins-name "integration-workflow-20240101"`,
			RunE: func(cmd *cobra.Command, args []string) error {
				if dagInsID == "" {
					return fmt.Errorf("--dag-ins-id must be provided")
				}

				// Initialize fastflow if needed
				if err := initializeFastflow(); err != nil {
					return fmt.Errorf("failed to initialize fastflow: %w", err)
				}

				fmt.Printf("Retrying DAG instance: %s\n", dagInsID)
				if err := mod.GetCommander().RetryDagIns(dagInsID); err != nil {
					return fmt.Errorf("failed to retry DAG instance '%s': %w", dagInsID, err)
				}

				fmt.Printf("✅ DAG instance '%s' retry request submitted successfully\n", dagInsID)
				return nil
			},
		}
		retryCmd.Flags().StringVarP(&dagInsID, "dag-ins-id", "i", "", "DAG instance ID to retry")
		cmd.AddCommand(retryCmd)
	}

	// Cancel DAG instance command
	{
		var dagInsID string
		cancelCmd := &cobra.Command{
			Use:   "cancel-dag-ins",
			Short: "Cancel a running DAG instance",
			Long: `Cancel a running DAG instance by DAG instance ID.
			
This command cancels a running DAG instance in the fastflow workflow system.
It will stop the DAG instance and mark it as cancelled.`,
			Example: `  # Cancel a DAG instance by ID
  job workflow cancel-dag-ins --dag-ins-id "abc123"
  
  # Cancel a DAG instance by name
  job workflow cancel-dag-ins --dag-ins-name "integration-workflow-20240101"
  
  # Force cancel a DAG instance
  job workflow cancel-dag-ins --dag-ins-id "abc123" --force`,
			RunE: func(cmd *cobra.Command, args []string) error {
				if dagInsID == "" {
					return fmt.Errorf("--dag-ins-id must be provided")
				}

				// Initialize fastflow if needed
				if err := initializeFastflow(); err != nil {
					return fmt.Errorf("failed to initialize fastflow: %w", err)
				}

				if err := mod.GetCommander().CancelDagIns(dagInsID); err != nil {
					return fmt.Errorf("failed to cancel DAG instance '%s': %w", dagInsID, err)
				}

				fmt.Printf("✅ DAG instance '%s' cancel request submitted successfully\n", dagInsID)
				return nil
			},
		}
		cancelCmd.Flags().StringVarP(&dagInsID, "dag-ins-id", "i", "", "DAG instance ID to cancel")
		cmd.AddCommand(cancelCmd)
	}
}

// initializeFastflow initializes the fastflow system if not already initialized
func initializeFastflow() error {
	// Register actions first
	action.RegisterAction()
	// Initialize fastflow using DI
	return di.DiCall(func() error {
		// The fastflow initialization should already be done through DI
		// This is just to ensure it's properly set up
		return nil
	})
}

func init() {
	fastflowCmd := &cobra.Command{
		Use:   "workflow",
		Short: "Manage fastflow workflow DAG instances",
		Long: `Manage fastflow workflow DAG instances.
		
This command provides subcommands to manage DAG instances in the fastflow workflow system,
including retrying failed instances, cancelling running instances, and listing instances.`,
		Example: `  # Retry a failed DAG instance
  job workflow retry-dag-ins --dag-ins-id "abc123"
  
  # Cancel a running DAG instance
  job workflow cancel-dag-ins --dag-ins-id "abc123"
  `,
		PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
			// Initialize workflow context if needed
			ctx := context.Background()
			cmd.SetContext(ctx)
			return nil
		},
	}

	registerFastflowJobFunc(fastflowCmd)
	jobCmd.AddCommand(fastflowCmd)
}
