// Package main is the entry point for the ToolHive CLI Doc Generator.
package main

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

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

	cli "github.com/stacklok/toolhive-registry-server/cmd/thv-registry-api/app"
)

// fmTemplate is the front matter template for the generated markdown files.
const fmTemplate = `---
title: %s
hide_title: true
description: %s
last_update:
  author: autogenerated
slug: %s
mdx:
  format: md
---

`

// filePrepender generates the front matter for each markdown file.
func filePrepender(filename string) string {
	name := filepath.Base(filename)
	base := strings.TrimSuffix(name, path.Ext(name))
	title := strings.ReplaceAll(base, "_", " ")
	description := fmt.Sprintf("Reference for ToolHive Registry API CLI command `%s`", title)
	return fmt.Sprintf(fmTemplate, title, description, base)
}

// linkHandler processes links in the markdown files.
func linkHandler(filename string) string {
	// Return the filename as-is for relative links
	return filename
}

func main() {
	var dir string
	root := &cobra.Command{
		Use:          "gendoc",
		Short:        "Generate ToolHive's help docs",
		SilenceUsage: true,
		Args:         cobra.NoArgs,
		RunE: func(*cobra.Command, []string) error {
			return doc.GenMarkdownTreeCustom(cli.NewRootCmd(), dir, filePrepender, linkHandler)
		},
	}
	root.Flags().StringVarP(&dir, "dir", "d", "doc", "Path to directory in which to generate docs")
	if err := root.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}
