package command

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

// PromptCommand maps a command name to its prompt content loaded from a .md file.
type PromptCommand struct {
	Name    string // filename without .md extension
	Content string // file content (the prompt text)
}

// LoadPromptCommands scans dir for .md files and returns one PromptCommand per file.
// Returns nil (no error) if the directory does not exist.
func LoadPromptCommands(dir string) ([]PromptCommand, error) {
	entries, err := os.ReadDir(dir)
	if err != nil {
		if os.IsNotExist(err) {
			return nil, nil
		}
		return nil, err
	}

	var prompts []PromptCommand
	for _, e := range entries {
		if e.IsDir() || !strings.HasSuffix(e.Name(), ".md") {
			continue
		}
		data, err := os.ReadFile(filepath.Join(dir, e.Name()))
		if err != nil {
			continue
		}
		name := strings.TrimSuffix(e.Name(), ".md")
		prompts = append(prompts, PromptCommand{
			Name:    name,
			Content: strings.TrimSpace(string(data)),
		})
	}
	return prompts, nil
}

// ExpandPrompt builds the final message by concatenating the prompt content
// with any extra arguments the user provided after the command.
func ExpandPrompt(content string, args []string) string {
	if len(args) == 0 {
		return content
	}
	return content + "\n\n" + strings.Join(args, " ")
}
