// Copyright 2013-2022 The Cobra Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package doc

import (
	"bytes"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"sort"
	"strings"
	"time"

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

// formatFlags formats options and aliases as list of code elements. E.g., ["--help", "-h"] becomes "`--help`, `-h`".
func formatFlags(input []string) string {
	return fmt.Sprintf("`%s`", strings.Join(input, "`, `"))
}

// formatDescription replaces line breaks in descriptions with <br/> elements to avoid breaking table formatting.
func formatDescription(input string) string {
	return strings.Replace(input, "\n", "<br/>", -1)
}

// sprintOptionsTable renders options in table to make them more accessible.
func sprintOptionsTable(flags *pflag.FlagSet) string {
	output := "| Option | Description |\n"
	output += "| ------ | ----------- |\n"

	flags.VisitAll(func(flag *pflag.Flag) {
		flags := []string{"--" + flag.Name}
		if flag.Shorthand != "" && flag.ShorthandDeprecated == "" {
			flags = append(flags, "-"+flag.Shorthand)
		}

		description := flag.Usage
		if flag.DefValue != "" {
			description += fmt.Sprintf("\nDefault: `%s`", flag.DefValue)
		}

		row := fmt.Sprintf("| %s | %s |\n", formatFlags(flags), formatDescription(description))
		output += row
	})

	return output
}

func sprintOptions(cmd *cobra.Command, name string) string {
	output := ""

	flags := cmd.NonInheritedFlags()
	if flags.HasAvailableFlags() {
		output += "### Options\n\n"
		output += sprintOptionsTable(flags)
		output += "\n"
	}

	parentFlags := cmd.InheritedFlags()
	if parentFlags.HasAvailableFlags() {
		output += "### Global options\n\n"
		output += sprintOptionsTable(parentFlags)
		output += "\n"
	}

	return output
}

// GenMarkdown creates markdown output.
func GenMarkdown(cmd *cobra.Command, w io.Writer) error {
	return GenMarkdownCustom(cmd, w, func(s string) string { return s })
}

// GenMarkdownCustom creates custom markdown output.
func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error {
	cmd.InitDefaultHelpCmd()
	cmd.InitDefaultHelpFlag()

	buf := new(bytes.Buffer)
	name := cmd.CommandPath()

	buf.WriteString("## " + name + "\n\n")
	if len(cmd.Long) > 0 {
		buf.WriteString(cmd.Long + "\n\n")
	} else {
		buf.WriteString(cmd.Short + "\n\n")
	}

	if cmd.Runnable() {
		buf.WriteString(fmt.Sprintf("```\n%s\n```\n\n", cmd.UseLine()))
	}

	if len(cmd.Aliases) > 0 {
		buf.WriteString("### Aliases\n\n")
		buf.WriteString(fmt.Sprintf("%s\n\n", formatFlags(cmd.Aliases)))
	}

	if len(cmd.Example) > 0 {
		buf.WriteString("### Examples\n\n")
		buf.WriteString(fmt.Sprintf("```\n%s\n```\n\n", cmd.Example))
	}

	buf.WriteString(sprintOptions(cmd, name))

	if hasSeeAlso(cmd) {
		buf.WriteString("### Related commands\n\n")
		buf.WriteString("| Command | Description |\n")
		buf.WriteString("| ------- | ----------- |\n")

		if cmd.HasParent() {
			parent := cmd.Parent()
			pname := parent.CommandPath()
			link := pname + ".md"
			link = strings.ReplaceAll(link, " ", "_")
			buf.WriteString(fmt.Sprintf("| [%s](%s) | %s |\n", pname, linkHandler(link), formatDescription(parent.Short)))
			cmd.VisitParents(func(c *cobra.Command) {
				if c.DisableAutoGenTag {
					cmd.DisableAutoGenTag = c.DisableAutoGenTag
				}
			})
		}

		children := cmd.Commands()
		sort.Sort(byName(children))

		for _, child := range children {
			if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() {
				continue
			}
			cname := name + " " + child.Name()
			link := cname + ".md"
			link = strings.ReplaceAll(link, " ", "_")
			buf.WriteString(fmt.Sprintf("| [%s](%s) | %s |\n", cname, linkHandler(link), formatDescription(child.Short)))
		}
		buf.WriteString("\n")
	}

	if !cmd.DisableAutoGenTag {
		buf.WriteString("###### Auto generated by spf13/cobra on " + time.Now().Format("2-Jan-2006") + "\n")
	}
	_, err := buf.WriteTo(w)
	return err
}

// GenMarkdownTree will generate a markdown page for this command and all
// descendants in the directory given. The header may be nil.
// This function may not work correctly if your command names have `-` in them.
// If you have `cmd` with two subcmds, `sub` and `sub-third`,
// and `sub` has a subcommand called `third`, it is undefined which
// help output will be in the file `cmd-sub-third.1`.
func GenMarkdownTree(cmd *cobra.Command, dir string) error {
	identity := func(s string) string { return s }
	emptyStr := func(s string) string { return "" }
	return GenMarkdownTreeCustom(cmd, dir, emptyStr, identity)
}

// GenMarkdownTreeCustom is the the same as GenMarkdownTree, but
// with custom filePrepender and linkHandler.
func GenMarkdownTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error {
	for _, c := range cmd.Commands() {
		if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
			continue
		}
		if err := GenMarkdownTreeCustom(c, dir, filePrepender, linkHandler); err != nil {
			return err
		}
	}

	basename := strings.ReplaceAll(cmd.CommandPath(), " ", "_") + ".md"
	filename := filepath.Join(dir, basename)
	f, err := os.Create(filename)
	if err != nil {
		return err
	}
	defer f.Close()

	if _, err := io.WriteString(f, filePrepender(filename)); err != nil {
		return err
	}
	if err := GenMarkdownCustom(cmd, f, linkHandler); err != nil {
		return err
	}
	return nil
}