// Package semver is THE hub's controller/agent version comparator (house rule: one comparator).
// Extracted from web.compareVersions (v0.45.0) so the store's managed-floor MinAgent gate can share
// it without an import cycle (store/api don't import web). web.compareVersions now delegates here.
package semver

import (
	"strconv"
	"strings"
)

// Compare returns >0 if a>b, 0 if equal, <0 if a<b. Inputs are bare "X.Y.Z" (a leading "v" is
// tolerated). Returns 0 on any parse error — callers that must not act on a malformed version check
// for it explicitly before comparing.
func Compare(a, b string) int {
	a = strings.TrimPrefix(a, "v")
	b = strings.TrimPrefix(b, "v")
	ap := strings.SplitN(a, ".", 3)
	bp := strings.SplitN(b, ".", 3)
	if len(ap) != 3 || len(bp) != 3 {
		return 0
	}
	for i := 0; i < 3; i++ {
		ai, e1 := strconv.Atoi(ap[i])
		bi, e2 := strconv.Atoi(bp[i])
		if e1 != nil || e2 != nil {
			return 0
		}
		if ai != bi {
			if ai < bi {
				return -1
			}
			return 1
		}
	}
	return 0
}

// Valid reports whether s is a bare X.Y.Z (v-prefix tolerated) — the shape Compare acts on.
func Valid(s string) bool {
	s = strings.TrimPrefix(s, "v")
	p := strings.SplitN(s, ".", 3)
	if len(p) != 3 {
		return false
	}
	for _, part := range p {
		if _, err := strconv.Atoi(part); err != nil {
			return false
		}
	}
	return true
}
