/**
 * Shared input-validation primitives for SF tool handlers.
 */
/** Type guard: value is a string with at least one non-whitespace character. */
export function isNonEmptyString(value) {
	return typeof value === "string" && value.trim().length > 0;
}
const LEAKED_JSON_FIELD_RE =
	/(^|[,{]\s*)"(?:successCriteria|proofLevel|integrationClosure|observabilityImpact|planningMeeting|visionMeeting|productResearch|tasks|updatedTasks|removedTaskIds|verify|expectedOutput|oneLiner|narrative|verification|uatContent|keyFiles|keyDecisions|deviations|knownIssues|knownLimitations|followUps|operationalReadiness)"\s*:|",\s*"[A-Za-z][A-Za-z0-9_]*"\s*:/;
/**
 * Normalize freeform model-authored markdown fields before persistence.
 * Tool schemas prove the outer type, but models can still pass JSON-ish debris
 * or escaped newlines inside a valid string.
 */
export function normalizePlanningText(value, field) {
	const normalized = value.replace(/\\n/g, "\n").trim();
	if (LEAKED_JSON_FIELD_RE.test(normalized)) {
		throw new Error(`${field} appears to contain leaked JSON fields`);
	}
	return normalized;
}
export function normalizeRequiredPlanningText(value, field) {
	const normalized = normalizePlanningText(value, field);
	if (normalized.length === 0) {
		throw new Error(`${field} must be a non-empty string`);
	}
	return normalized;
}
export function validateSafePathSegment(value, field) {
	const normalized = normalizeRequiredPlanningText(value, field);
	if (
		normalized === "." ||
		normalized === ".." ||
		normalized.includes("/") ||
		normalized.includes("\\") ||
		/[\0\r\n]/.test(normalized)
	) {
		throw new Error(`${field} must be a safe path segment`);
	}
	return normalized;
}
export function normalizePlanningTextArray(value, field) {
	return validateStringArray(value, field).map((item, index) =>
		normalizePlanningText(item, `${field}[${index}]`),
	);
}
/**
 * Validate that `value` is an array of non-empty strings.
 * Throws with a message referencing `field` on failure.
 * Returns the validated array (narrowed to string[]).
 */
export function validateStringArray(value, field) {
	if (!Array.isArray(value)) {
		throw new Error(`${field} must be an array`);
	}
	if (value.some((item) => !isNonEmptyString(item))) {
		throw new Error(`${field} must contain only non-empty strings`);
	}
	return value;
}
