package toolingplan

import (
	"encoding/json"
	"regexp"
	"strings"
)

var (
	exactVersionPattern = regexp.MustCompile(`^v?\d+(?:\.\d+){0,2}(?:[-+][0-9A-Za-z.-]+)?$`)
	goDirectivePattern  = regexp.MustCompile(`(?m)^go\s+([0-9]+(?:\.[0-9]+){1,2})\s*$`)
)

func normalizeExactVersion(value string) (string, bool) {
	trimmed := strings.TrimSpace(value)
	if !exactVersionPattern.MatchString(trimmed) {
		return "", false
	}
	return strings.TrimPrefix(trimmed, "v"), true
}

func parseGoDirective(goMod string) (string, bool) {
	matches := goDirectivePattern.FindStringSubmatch(goMod)
	if len(matches) != 2 {
		return "", false
	}
	return matches[1], true
}

type packageJSONMetadata struct {
	PackageManager string `json:"packageManager"`
	Volta          struct {
		Node string `json:"node"`
	} `json:"volta"`
}

func parsePackageJSON(data string) (packageJSONMetadata, error) {
	var meta packageJSONMetadata
	err := json.Unmarshal([]byte(data), &meta)
	return meta, err
}
