package parser

import (
	"context"
	"errors"
	"strings"

	"bit.admedia.com/scm/ad/adpilot-indexing-code-parser.com/internal/contracts/graph"
	"bit.admedia.com/scm/ad/adpilot-indexing-code-parser.com/internal/store"
)

// ErrCommitArtifactsNotReady indicates commit diff artifacts are not yet available.
var ErrCommitArtifactsNotReady = errors.New("commit graph artifacts not ready")

func (s *Service) codeParseReady(ctx context.Context, repoID, snapshotID string) (bool, error) {
	return s.ensureCodeParseFanInSynced(ctx, repoID, snapshotID)
}

func (s *Service) findTargetArtifact(
	ctx context.Context,
	repoID, snapshotID, commitSHA, filePath string,
) (graph.Artifact, string, error) {
	artifact, id, err := s.artifacts.FindArtifactByCommitFile(ctx, repoID, commitSHA, filePath)
	if err == nil {
		return artifact, id, nil
	}
	if !errors.Is(err, store.ErrArtifactNotFound) {
		return graph.Artifact{}, "", err
	}

	artifact, id, err = s.artifacts.FindArtifactBySnapshotFile(ctx, repoID, snapshotID, filePath)
	if err != nil {
		return graph.Artifact{}, "", err
	}
	return artifact, id, nil
}

func (s *Service) findBaseArtifact(
	ctx context.Context,
	repoID, snapshotID, commitSHA, filePath string,
	rootCommit bool,
) (graph.Artifact, string, error) {
	if rootCommit {
		return graph.Artifact{}, "", nil
	}

	artifact, id, err := s.artifacts.FindArtifactByCommitFile(ctx, repoID, commitSHA, filePath)
	if err == nil {
		return artifact, id, nil
	}
	if errors.Is(err, store.ErrArtifactNotFound) {
		return graph.Artifact{}, "", nil
	}
	return graph.Artifact{}, "", err
}

func missingArtifactsAllTargets(labels []string) bool {
	if len(labels) == 0 {
		return false
	}
	for _, label := range labels {
		if !strings.HasPrefix(label, "target:") {
			return false
		}
	}
	return true
}
