package cms

import (
	"fmt"
	"io/fs"
	"os"
	"path/filepath"
)

func LoadSections(root string) (map[string]Section, error) {
	dir := filepath.Join(root, "site/sections")
	sections := map[string]Section{}
	if _, err := os.Stat(dir); err != nil {
		if os.IsNotExist(err) {
			return sections, nil
		}
		return nil, err
	}
	err := filepath.WalkDir(dir, func(path string, entry fs.DirEntry, err error) error {
		if err != nil {
			return err
		}
		if entry.IsDir() || filepath.Ext(path) != ".toml" {
			return nil
		}
		section, err := loadSection(path)
		if err != nil {
			return err
		}
		sections[section.Name] = section
		return nil
	})
	return sections, err
}

func loadSection(path string) (Section, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return Section{}, err
	}
	table, err := parseSimpleTable(string(data))
	if err != nil {
		return Section{}, fmt.Errorf("%s: %w", path, err)
	}
	name := table.values["name"]
	if name == "" {
		name = slugify(filepath.Base(path))
	}
	title := table.values["title"]
	if title == "" {
		title = titleize(name)
	}
	return Section{Name: name, Title: title}, nil
}
