package run

import "strings"

// public failure identity bounds shared by every producer and read
// projector so a durable failure receipt validates and round-trips through one
// grammar. A valid identity is a closed vocabulary; an oversized or malformed
// value fails closed and is NEVER truncated into a different valid identity.
const (
	// PublicFailureCodeRunes bounds a failure code identity.
	PublicFailureCodeRunes = 128
	// PublicFailurePathRunes bounds a failure path identity.
	PublicFailurePathRunes = 1024
	// PublicFailureStageRunes bounds a failure stage identity.
	PublicFailureStageRunes = 64
	// PublicPlanPortRunes bounds a compiled/authored Plan output port identity.
	PublicPlanPortRunes = 64
	// PublicDiagnosticFieldRunes bounds a diagnostic field-name identity.
	PublicDiagnosticFieldRunes = 128
)

// PublicDiagnosticField validates a diagnostic field-name identity
// byte-for-byte. A diagnostic field names a JSON property in the authored/
// compiled input (for example `body`, `key`, `responder`, `dependsOn`), so it
// may be camelCase; it must be ASCII letters/digits/underscore/hyphen only. A
// spaced, malformed-UTF-8, punctuation-bearing, secret-bearing, or oversized
// value fails closed and is never trimmed or sanitized into a different valid
// identity.
func PublicDiagnosticField(field string) (string, bool) {
	if field == "" || len(field) > PublicDiagnosticFieldRunes {
		return "", false
	}
	for index := 0; index < len(field); index++ {
		character := field[index]
		if (character >= 'a' && character <= 'z') ||
			(character >= 'A' && character <= 'Z') ||
			(character >= '0' && character <= '9') ||
			character == '_' || character == '-' {
			continue
		}
		return "", false
	}
	return field, true
}

// PublicPlanPort validates a compiled/authored Plan output port identity
// byte-for-byte against the authoritative grammar ^[a-z][a-z0-9_-]{0,63}$. The
// value is never TrimSpace'd or UTF-8-sanitized into a different valid identity:
// surrounding whitespace, malformed UTF-8, punctuation, uppercase, or an
// oversized value fails closed.
func PublicPlanPort(port string) (string, bool) {
	if port == "" || len(port) > PublicPlanPortRunes {
		return "", false
	}
	first := port[0]
	if first < 'a' || first > 'z' {
		return "", false
	}
	for index := 1; index < len(port); index++ {
		character := port[index]
		if (character >= 'a' && character <= 'z') ||
			(character >= '0' && character <= '9') ||
			character == '_' || character == '-' {
			continue
		}
		return "", false
	}
	return port, true
}

// publicFailureStageVocabulary is the closed set of failure stages produced
// by the runtime. Any other string (including secret-bearing or malformed prose)
// fails closed.
var publicFailureStageVocabulary = map[string]struct{}{
	"dispatch": {}, "reducer": {}, "work_item": {}, "callback": {},
	"material": {}, "storage": {}, "recovery": {}, "approval": {},
}

// PublicFailureCode validates the FULL failure code identity and returns it
// unchanged only when every byte matches the stable grammar (dot-separated
// segments of lowercase letters, digits, underscores, and hyphens) and the whole
// value is within the rune bound. The value is validated byte-for-byte: no
// leading/trailing whitespace, no malformed UTF-8, and no other punctuation is
// ever accepted or normalized into a different valid identity. An oversized or
// malformed value returns false so callers fail closed instead of truncating
// into a different valid identity.
func PublicFailureCode(code string) (string, bool) {
	if code == "" || len([]rune(code)) > PublicFailureCodeRunes {
		return "", false
	}
	for _, segment := range strings.Split(code, ".") {
		if segment == "" {
			return "", false
		}
		for _, character := range segment {
			if (character >= 'a' && character <= 'z') ||
				(character >= '0' && character <= '9') ||
				character == '_' || character == '-' {
				continue
			}
			return "", false
		}
	}
	return code, true
}

// PublicFailureStage validates a stage identity against the closed producer
// vocabulary. Unknown or malformed values fail closed. The value is matched
// byte-for-byte: surrounding whitespace or a malformed UTF-8 variant of a
// vocabulary word is never trimmed or sanitized into the accepted identity.
func PublicFailureStage(stage string) (string, bool) {
	if _, ok := publicFailureStageVocabulary[stage]; !ok {
		return "", false
	}
	return stage, true
}

// PublicFailurePath validates a structured kernel failure path identity: a
// node id, a `$.` JSON-pointer reference, or a WorkItem dependency path. Allowed
// bytes are ASCII word chars plus `.`, `_`, `-`, `/`, `$`, `[`, `]`. No
// surrounding or internal whitespace, no malformed UTF-8, and no other
// punctuation. An oversized or free-form value fails closed.
func PublicFailurePath(path string) (string, bool) {
	if path == "" || len(path) > PublicFailurePathRunes {
		return "", false
	}
	for _, character := range path {
		if (character >= 'a' && character <= 'z') ||
			(character >= 'A' && character <= 'Z') ||
			(character >= '0' && character <= '9') ||
			character == '.' || character == '_' || character == '-' ||
			character == '/' || character == '$' || character == '[' || character == ']' {
			continue
		}
		return "", false
	}
	return path, true
}

// PublicWorkItemKey validates a WorkItem key identity with the authoritative
// 256-byte WorkItem grammar: ^[a-z][a-z0-9_-]{0,255}$ (a lowercase letter start,
// then lowercase letters, digits, underscores, or hyphens; at most 256 bytes).
// The key MUST start with a lowercase letter and must NOT contain a dot. Every
// byte is validated exactly: leading/trailing whitespace, malformed UTF-8, an
// uppercase-leading or dot-bearing value fails closed rather than being
// normalized into a different valid identity.
func PublicWorkItemKey(key string) (string, bool) {
	if key == "" || len(key) > 256 || key[0] < 'a' || key[0] > 'z' {
		return "", false
	}
	for index := 1; index < len(key); index++ {
		value := key[index]
		if (value >= 'a' && value <= 'z') ||
			(value >= '0' && value <= '9') ||
			value == '_' || value == '-' {
			continue
		}
		return "", false
	}
	return key, true
}

// ValidDependencyPath validates a WorkItem dependency path identity.
func ValidDependencyPath(path string) (string, bool) {
	return PublicFailurePath(path)
}
