package cmd

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/spf13/cobra"
	"github.com/spf13/cobra/doc"
)

var manpagesCmd = &cobra.Command{
	Use:   "manpages",
	Short: "Generate manpages",
	Long:  "Generate manpages for fj commands.",
	RunE: func(cmd *cobra.Command, args []string) error {
		dir, _ := cmd.Flags().GetString("dir")
		if dir == "" {
			return fmt.Errorf("directory is required")
		}

		if err := os.MkdirAll(dir, 0755); err != nil {
			return fmt.Errorf("failed to create %s: %w", dir, err)
		}

		absDir, err := filepath.Abs(dir)
		if err != nil {
			return fmt.Errorf("failed to resolve %s: %w", dir, err)
		}

		header := &doc.GenManHeader{
			Title:   "FGJ",
			Section: "1",
		}

		if err := doc.GenManTree(rootCmd, header, absDir); err != nil {
			return fmt.Errorf("failed to generate manpages: %w", err)
		}

		fmt.Printf("Manpages generated in %s\n", absDir)
		return nil
	},
}

func init() {
	rootCmd.AddCommand(manpagesCmd)
	manpagesCmd.Flags().String("dir", "", "Output directory for manpages")
	_ = manpagesCmd.MarkFlagRequired("dir")
}
