package runner

import (
	"fmt"
	"strings"

	"github.com/easyai/easyai-ai-gateway/apps/api/internal/store"
)

func filterCandidatesByRequestedPlatform(
	candidates []store.RuntimeModelCandidate,
	body map[string]any,
) ([]store.RuntimeModelCandidate, error) {
	platformID := firstNonEmptyString(
		stringFromAny(body["platform_id"]),
		stringFromAny(body["platformId"]),
	)
	platformModelID := firstNonEmptyString(
		stringFromAny(body["platform_model_id"]),
		stringFromAny(body["platformModelId"]),
	)
	if platformID == "" && platformModelID == "" {
		return candidates, nil
	}

	filtered := make([]store.RuntimeModelCandidate, 0, len(candidates))
	for _, candidate := range candidates {
		if platformID != "" && !strings.EqualFold(candidate.PlatformID, platformID) {
			continue
		}
		if platformModelID != "" && !strings.EqualFold(candidate.PlatformModelID, platformModelID) {
			continue
		}
		filtered = append(filtered, candidate)
	}
	if len(filtered) > 0 {
		return filtered, nil
	}

	requested := platformID
	if platformModelID != "" {
		requested = platformModelID
	}
	return nil, fmt.Errorf(
		"%w: requested platform %q is unavailable for this model",
		store.ErrNoModelCandidate,
		requested,
	)
}
