package server

import (
	"fmt"
	"regexp"

	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/gitaly/vendored/gitalypb"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/agent_configuration"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/managed_resources"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/managed_resources/rpc"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/server_api"
)

var (
	templatesFileRegex = regexp.MustCompile(fmt.Sprintf(`^%s/(%s)/%s/([^/]+)\.yaml$`,
		regexp.QuoteMeta(agent_configuration.Directory),
		server_api.AgentNameRegex,
		regexp.QuoteMeta(managed_resources.TemplatesDirectory),
	))
)

type templateVisitor struct {
	infos []*rpc.EnvironmentTemplateInfo
}

func (v *templateVisitor) Entry(entry *gitalypb.TreeEntry) (bool /* download? */, int64 /* max size */, error) {
	submatch := templatesFileRegex.FindSubmatch(entry.Path)
	if submatch == nil {
		return false, 0, nil
	}
	v.infos = append(v.infos, &rpc.EnvironmentTemplateInfo{
		AgentName:    string(submatch[1]),
		TemplateName: string(submatch[2]),
	})
	return false, 0, nil
}

func (v *templateVisitor) StreamChunk(path, data []byte) (bool, error) {
	return false, nil
}

func (v *templateVisitor) EntryDone(entry *gitalypb.TreeEntry, err error) {}
