package cli

import (
	"github.com/spf13/cobra"

	"github.com/tidbcloud/observability/vm-migration/internal/plan"
	"github.com/tidbcloud/observability/vm-migration/internal/printer"
)

// newPlanCompileCmd returns the plan compile command.
//
// Accepts --plan-path (default: plan.json) and --tenants flags.
func newPlanCompileCmd() *cobra.Command {
	var o plan.CompileOptions
	cmd := &cobra.Command{
		Use:   "compile",
		Short: "Compile plan.json with its tenant inventory for review",
		Long: `Validates plan.json and a merged tenant list, resolves static
configuration placeholders, and embeds the flat tenant ids in one compact
compiled plan. Tenant-specific command placeholders remain unexpanded.

This command never writes migration-loop.json or per-tenant files. POST it
to a running serve (` + "`POST /migrations/{name}`" + `) to expand tenant commands and
materialize the runtime directory
consumed by ` + "`serve`" + `.`,
		Args:         cobra.NoArgs,
		SilenceUsage: true,
		Example: `  vm-migration plan compile --tenants tenants.json

  # Custom plan path
  vm-migration plan compile --plan-path envs/prod/plan.json \
    --tenants envs/prod/tenants.json`,
		RunE: func(cmd *cobra.Command, args []string) error {
			result, err := plan.Compile(o)
			if err != nil {
				return err
			}
			printer.Printf(cmd.OutOrStdout(), "plan compile: wrote %s", result.CompilePath)
			return nil
		},
	}
	cmd.Flags().StringVar(&o.Plan, "plan-path", "plan.json", "Path to plan.json")
	cmd.Flags().StringVar(&o.Tenants, "tenants", "", "Path to merged flat tenant list JSON")
	cmd.Flags().StringVar(&o.Output, "output", "", "Output file (default <plan-stem>-compile.json next to input)")
	mustMarkRequired(cmd, "tenants")
	return cmd
}
