// SPDX-FileCopyrightText: Copyright 2025 Stacklok, Inc.
// SPDX-License-Identifier: Apache-2.0

// 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/cmd/thv/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 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(false), 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)
	}
}
