package model

import "strings"

// IngressID returns the model name exposed to ingress API clients.
func (m ModelEntry) IngressID() string {
	if m.Alias != "" {
		return m.Alias
	}
	return m.ModelID
}

// SplitIngressOwnerName splits an ingress model identifier into Replicate owner/name parts.
func SplitIngressOwnerName(ingressID, providerName string) (owner, name string) {
	if i := strings.Index(ingressID, "/"); i > 0 {
		return ingressID[:i], ingressID[i+1:]
	}
	owner = providerName
	if owner == "" {
		owner = "luminary"
	}
	name = ingressID
	if name == "" {
		name = "model"
	}
	return owner, name
}

// OwnerName returns the Replicate-style owner/name for an ingress model entry.
func (m ModelEntry) OwnerName(providerName string) (string, string) {
	return SplitIngressOwnerName(m.IngressID(), providerName)
}

// MatchesIngressName reports whether the entry matches an ingress model identifier.
func (m ModelEntry) MatchesIngressName(name string) bool {
	if name == "" || !m.Enabled {
		return false
	}
	if m.ModelID == name || m.VersionHash == name {
		return true
	}
	return m.Alias != "" && m.Alias == name
}

// MatchesIngressRef reports whether ref identifies this model (ingress ID, owner/name, or short name).
func (m ModelEntry) MatchesIngressRef(ref, providerName string) bool {
	if !m.Enabled || ref == "" {
		return false
	}
	if m.MatchesIngressName(ref) {
		return true
	}
	owner, name := m.OwnerName(providerName)
	if ref == name || ref == owner+"/"+name {
		return true
	}
	return false
}
