package listing

import (
	"net/url"
	"os"
)

// FromDirEntries converts os.DirEntry slice to []FileInfo.
// baseURL is the URL prefix for this directory (must end with "/").
// Entries starting with "." or "_" are excluded (see filter below).
func FromDirEntries(entries []os.DirEntry, baseURL string) ([]FileInfo, error) {
	var result []FileInfo
	for _, entry := range entries {
		name := entry.Name()

		// Skip hidden entries. '.' and '_' are both reserved prefixes:
		// '.' marks system/internal state (.zddc files, .archive virtual
		// path, .admin debug page, dev-shell home dirs); '_' marks operator
		// scaffolding like install.zip's _template/ directory that's
		// reachable by direct URL but should not appear in browse listings.
		if len(name) == 0 || name[0] == '.' || name[0] == '_' {
			continue
		}

		info, err := entry.Info()
		if err != nil {
			continue
		}

		isDir := entry.IsDir()
		entryName := name
		entryURL := baseURL + url.PathEscape(name)
		if isDir {
			entryName = name + "/"
			entryURL = baseURL + url.PathEscape(name) + "/"
		}

		fi := FileInfo{
			Name:      entryName,
			Size:      info.Size(),
			URL:       entryURL,
			ModTime:   info.ModTime(),
			Mode:      uint32(info.Mode()),
			IsDir:     isDir,
			IsSymlink: false,
		}
		result = append(result, fi)
	}
	return result, nil
}
