package recipe

import (
	"errors"
	"fmt"
	"os"
	"path"
	"strings"

	"coopcloud.tech/abra/pkg/envfile"
	"coopcloud.tech/abra/pkg/formatter"
	"coopcloud.tech/abra/pkg/i18n"
)

func (r Recipe) SampleEnv() (map[string]string, error) {
	sampleEnv, err := envfile.ReadEnv(r.SampleEnvPath)
	if err != nil {
		return sampleEnv, errors.New(i18n.G(".env.sample for %s couldn't be read: %s", r.Name, err))
	}
	return sampleEnv, nil
}

// GetReleaseNotes prints release notes for the recipe version
func (r Recipe) GetReleaseNotes(version, appDomain string) (string, error) {
	if version == "" {
		return "", nil
	}

	fpath := path.Join(r.Dir, "release", version)

	if _, err := os.Stat(fpath); !os.IsNotExist(err) {
		releaseNotes, err := os.ReadFile(fpath)
		if err != nil {
			return "", err
		}

		title := formatter.BoldStyle.Render(i18n.G("%s release notes:", version))
		withTitle := fmt.Sprintf("%s\n%s\n", title, releaseNotes)

		templatedDomain := strings.Replace(
			withTitle,
			fmt.Sprintf("%s.example.com", r.Name),
			appDomain,
			-1,
		)

		return templatedDomain, nil
	}

	return "", nil
}
