package rpm

import (
	"bytes"
	"fmt"
	"path/filepath"
	"runtime/debug"

	"github.com/Azure/dalec"
	"github.com/moby/buildkit/client/llb"
)

func ToSpecLLB(spec *dalec.Spec, in llb.State, targetKey, dir string, opts ...llb.ConstraintsOpt) (llb.State, error) {
	if err := ValidateSpec(spec); err != nil {
		return llb.Scratch(), fmt.Errorf("invalid spec: %w", err)
	}
	opts = append(opts, dalec.ProgressGroup("Generate RPM spec"))
	buf := bytes.NewBuffer(nil)
	info, _ := debug.ReadBuildInfo()
	buf.WriteString("# Automatically generated by " + info.Main.Path + "\n")
	buf.WriteString("\n")

	if err := WriteSpec(spec, targetKey, buf); err != nil {
		return llb.Scratch(), err
	}

	if dir == "" {
		dir = "SPECS/" + spec.Name
	}

	return in.
			File(llb.Mkdir(dir, 0755, llb.WithParents(true)), opts...).
			File(llb.Mkfile(filepath.Join(dir, spec.Name)+".spec", 0640, buf.Bytes()), opts...),
		nil
}

func SpecToBuildrootLLB(worker llb.State, spec *dalec.Spec, sOpt dalec.SourceOpts, targetKey string, opts ...llb.ConstraintsOpt) (llb.State, error) {
	if err := ValidateSpec(spec); err != nil {
		return llb.Scratch(), fmt.Errorf("invalid spec: %w", err)
	}
	opts = append(opts, dalec.ProgressGroup("Create RPM buildroot"))

	sources, err := ToSourcesLLB(worker, spec, sOpt, opts...)
	if err != nil {
		return llb.Scratch(), err
	}

	return ToSpecLLB(spec, dalec.MergeAtPath(llb.Scratch(), sources, "SOURCES"), targetKey, "", opts...)
}
