package templateversion

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

// LoadTemplatesFromPath reads all template files from the given directory
// and returns a map of template name (filename without extension) to content.
func LoadTemplatesFromPath(templatePath string) (map[string]string, error) {
	entries, err := os.ReadDir(templatePath)
	if err != nil {
		return nil, fmt.Errorf("read template path failed: %w", err)
	}

	const templExt = ".templ"
	ret := make(map[string]string, len(entries))
	for _, entry := range entries {
		if entry.IsDir() {
			continue
		}
		if filepath.Ext(entry.Name()) != templExt {
			continue
		}
		name := strings.TrimSuffix(entry.Name(), templExt)
		data, err := os.ReadFile(filepath.Join(templatePath, entry.Name()))
		if err != nil {
			return nil, fmt.Errorf("read template file %s failed: %w", entry.Name(), err)
		}
		ret[name] = string(data)
	}
	return ret, nil
}
