package partial

import (
	"fmt"
	"os"
	"strings"

	"git.clearsky.net.au/cody/gex.git/pkg/gen/domquery"
)

func ProcessHTML(htmlStr string) (string, error) {
	dom := domquery.LoadHTML(htmlStr)

	partTag := dom.QuerySelector("part")

	if partTag.TagName() == "" {
		return dom.OuterHTML(), nil
	}

	attr := partTag.GetAttribute("src")
	attr = strings.TrimPrefix(attr, "/")
	attr = strings.Replace(attr, ".tpl", ".gen.tpl", 1)

	partFileByt, err := os.ReadFile(attr)
	if err != nil {
		fmt.Printf("ERROR: %s", err)
		return "", err
	}
	partFileHtml := string(partFileByt)
	partFileDom := domquery.LoadHTML(partFileHtml)

	slot := partFileDom.QuerySelector("slot")
	if slot.TagName() != "" {
		slot.SetOuterHTML(partTag.InnerHTML())
	}
	partTag.SetOuterHTML(partFileDom.InnerHTML())

	htmlStr, err = ProcessHTML(dom.InnerHTML())
	if err != nil {
		fmt.Printf("ERROR: %s", err)
		return "", err
	}
	return htmlStr, nil
}
