package orch

import (
	"fmt"

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

	"github.com/spf13/cobra"
)

type cleanupOptions struct {
	runID        string
	taskID       string
	attemptNo    int
	allCompleted bool
	force        bool
}

func newCleanupCmd(root *rootOptions) *cobra.Command {
	opts := &cleanupOptions{}

	cmd := &cobra.Command{
		Use:   "cleanup",
		Short: "Remove completed or abandoned attempt worktrees",
		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()

			s := store.NewOrchStore(sqlDB)
			candidates, err := s.ListCleanupCandidates(ctx, store.CleanupInput{
				RunID:        opts.runID,
				TaskID:       opts.taskID,
				AttemptNo:    opts.attemptNo,
				AllCompleted: opts.allCompleted,
				Force:        opts.force,
			})
			if err != nil {
				return err
			}

			records := make([]store.CleanupRecord, 0, len(candidates))
			for _, candidate := range candidates {
				if err := cleanupAttemptWorktree(ctx, candidate.Attempt, opts.force); err != nil {
					return err
				}
				records = append(records, store.CleanupRecord{Attempt: candidate.Attempt})
			}

			cleaned, err := s.MarkAttemptsCleaned(ctx, records)
			if err != nil {
				return err
			}

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

			_, err = fmt.Fprintf(cmd.OutOrStdout(), "cleaned %d worktrees\n", len(cleaned))
			return err
		},
	}

	cmd.Flags().StringVar(&opts.runID, "run", "", "Run ID")
	cmd.Flags().StringVar(&opts.taskID, "task", "", "Optional task ID")
	cmd.Flags().IntVar(&opts.attemptNo, "attempt", 0, "Specific attempt number")
	cmd.Flags().BoolVar(&opts.allCompleted, "all-completed", false, "Clean all completed or abandoned worktrees in the run")
	cmd.Flags().BoolVar(&opts.force, "force", false, "Force cleanup even for non-terminal worktrees")
	_ = cmd.MarkFlagRequired("run")

	return cmd
}
