package server

import (
	"context"
	"fmt"
	"regexp"

	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/gitaly"
	"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/configuration_project/rpc"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/modserver"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/modshared"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/server_api"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/git"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/tool/logz"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

var (
	agentConfigFileRegex = regexp.MustCompile(fmt.Sprintf("^%s/(%s)/%s$",
		regexp.QuoteMeta(agent_configuration.Directory),
		server_api.AgentNameRegex,
		regexp.QuoteMeta(agent_configuration.FileName),
	))
)

type server struct {
	rpc.UnsafeConfigurationProjectServer
	gitaly gitaly.PoolInterface
}

func (s *server) ListAgentConfigFiles(ctx context.Context, req *rpc.ListAgentConfigFilesRequest) (*rpc.ListAgentConfigFilesResponse, error) {
	rpcAPI := modshared.RPCAPIFromContext[modserver.RPCAPI](ctx)
	pf, err := s.gitaly.PathFetcher(ctx, req.GitalyInfo)
	if err != nil {
		rpcAPI.HandleProcessingError(rpcAPI.Log(), "PathFetcher", err)
		return nil, status.Errorf(codes.Unavailable, "PathFetcher: %v", err)
	}
	v := &configVisitor{}
	ref := git.ExplicitRefOrHead(req.DefaultBranch)
	err = pf.Visit(ctx, req.Repository.ToGitalyRepository(), []byte(ref), []byte(agent_configuration.Directory), true, v)
	if err != nil {
		forwardErr := func() {
			log := rpcAPI.Log().With(logz.ProjectID(req.Repository.GlProjectPath))
			rpcAPI.HandleProcessingError(log, "PathFetcher", err)
		}
		switch gitaly.ErrorCodeFromError(err) { //nolint:exhaustive
		case gitaly.InvalidArgument:
			// We send this to Sentry anyway, because it shouldn't normally happen in this method.
			forwardErr()
			return nil, status.Errorf(codes.InvalidArgument, "PathFetcher: %v", err)
		case gitaly.NotFound:
			return &rpc.ListAgentConfigFilesResponse{}, nil
		default:
			forwardErr()
			return nil, status.Errorf(codes.Unavailable, "PathFetcher: %v", err)
		}
	}
	return &rpc.ListAgentConfigFilesResponse{
		ConfigFiles: v.resp,
	}, nil
}

type configVisitor struct {
	resp []*rpc.AgentConfigFile
}

func (c *configVisitor) Entry(entry *gitalypb.TreeEntry) (bool /* download? */, int64 /* max size */, error) {
	submatch := agentConfigFileRegex.FindSubmatch(entry.Path)
	if submatch == nil {
		return false, 0, nil
	}
	c.resp = append(c.resp, &rpc.AgentConfigFile{
		Name:      string(entry.Path),
		AgentName: string(submatch[1]),
	})
	return false, 0, nil
}

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

func (c *configVisitor) EntryDone(entry *gitalypb.TreeEntry, err error) {}
