filename="/usr/local/bin/md-validate.sh"

conf_print_md_validate_sh() {
	cat <<-'EOF'
		#!/usr/bin/env bash
		# Strict Level 3 validator

		if [ -z "$1" ]; then
			cat <<USAGE
			Usage: $(basename "$0") <file.md>
			USAGE
			exit 1
		fi

		INPUT_FILE="$1"

		IN_BLOCK=false
		BLOCK=""
		INDEX=0
		ERRORS=0
		FOUND=0

		validate_block() {
			local idx="$1"
			local content="$2"
			local block_errors=0

			if ! grep -q '^filename="/' <<< "$content"; then
				echo "[Block $idx] Missing absolute filename"
				((block_errors++))
			fi

			if ! grep -q 'conf_print_[a-zA-Z0-9_]\+()' <<< "$content"; then
				echo "[Block $idx] Missing conf_print function"
				((block_errors++))
			fi

			if ! grep -q "<<-'EOF'" <<< "$content"; then
				echo "[Block $idx] Missing strict heredoc"
				((block_errors++))
			fi

			if ! grep -q 'mkdir -p "$(dirname "${BUILD_DIR}${filename}")"' <<< "$content"; then
				echo "[Block $idx] Missing mkdir staging"
				((block_errors++))
			fi

			if ! grep -q 'tee "${BUILD_DIR}${filename}"' <<< "$content"; then
				echo "[Block $idx] Missing tee write"
				((block_errors++))
			fi

			FUNC=$(grep -oE '^conf_print_[a-zA-Z0-9_]+' <<< "$content" | head -n1)

			if [ -n "$FUNC" ]; then
				if ! grep -qE "${FUNC}[[:space:]]*\|[[:space:]]*tee" <<< "$content"; then
					echo "[Block $idx] Function not invoked via tee"
					((block_errors++))
				fi
			fi

			if [ "$block_errors" -eq 0 ]; then
				echo "[Block $idx] OK"
			else
				ERRORS=$((ERRORS + block_errors))
			fi
		}

		while IFS= read -r line || [ -n "$line" ]; do
			if [[ "$line" =~ ^\`\`\`bash ]]; then
				IN_BLOCK=true
				BLOCK=""
				INDEX=$((INDEX+1))
				FOUND=$((FOUND+1))
				continue
			fi

			if [[ "$line" =~ ^\`\`\` ]]; then
				if [ "$IN_BLOCK" = true ]; then
					validate_block "$INDEX" "$BLOCK"
					IN_BLOCK=false
				fi
				continue
			fi

			if [ "$IN_BLOCK" = true ]; then
				BLOCK+="$line"$'\n'
			fi
		done < "$INPUT_FILE"

		if [ "$FOUND" -eq 0 ]; then
			echo "[FAIL] No bash blocks found"
			exit 1
		fi

		if [ "$ERRORS" -eq 0 ]; then
			echo "[SUCCESS] Validation passed"
			exit 0
		else
			echo "[FAIL] $ERRORS issues found"
			exit 1
		fi
	EOF
}

mkdir -p "$(dirname "${BUILD_DIR}${filename}")"
conf_print_md_validate_sh | tee "${BUILD_DIR}${filename}" > /dev/null
