package cms

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

func LoadConfig(root string) (Config, error) {
	data, err := os.ReadFile(filepath.Join(root, "capsule.toml"))
	if err != nil {
		return Config{}, err
	}
	table, err := parseSimpleTable(string(data))
	if err != nil {
		return Config{}, fmt.Errorf("parse capsule.toml: %w", err)
	}
	cfg := Config{
		Title:    table.values["title"],
		Host:     table.values["host"],
		Author:   table.values["author"],
		Language: table.values["language"],
		Theme:    table.values["theme"],
	}
	if cfg.Language == "" {
		cfg.Language = "en"
	}
	if cfg.Theme == "" {
		cfg.Theme = "default"
	}
	return cfg, nil
}

func renderConfig(cfg Config) string {
	return "title = " + formatString(cfg.Title) + "\n" +
		"host = " + formatString(cfg.Host) + "\n" +
		"author = " + formatString(cfg.Author) + "\n" +
		"language = " + formatString(cfg.Language) + "\n" +
		"theme = " + formatString(cfg.Theme) + "\n"
}
