Plant development/genetics, like animal development/genetics (including us) is random, not directed. The plant phenotypes that happen to thrive in an environment (additionally in our case, those plants that are selected by human breeders for preferred effects) will be the ones with terpene profiles that will survive and go on. Further cross-breeding or other novel factors can also influence further change in the phenotype/chemotype. The 'reasons' for cannabis plants having the terpenes that they have will be down to evolutionary causes, genetic/epigenetic variations as well as human selective breeding.
One explanation in the literature for the survival of some terp profiles vs others is that they provided resistance to pests/predators. It has also been noted that some of the chemotypes that thrive are observed to have different terpene profiles at different heights of the plant, which provide resistance to the kinds of predators we would expect to find at the respective altitudes! This is a very fortunate evolutionary coincidence!
What I am saying is that cannabis plants do not think 'I need to smell a bit more blueberry-ish to suit this environmental requirement', nor is there any natural or supernatural process that makes a cannabis plant deliberately develop a set of terps for a specific purpose in the given environment.
The reason we can be tricked by evolution and natural processes into perceiving 'purpose' in the functions of living things is that those variations that suit the environment (or are selected and coddled by breeders in this case) will thrive and be the ones we tend to notice! On the other hand, those less useful genetic/epigenetic variations in phenotype/chemotype will lead to cannabis plants that do not thrive, are not selected by breeders and do not last in the natural environment for us to observe.
We cannot chart the development of cannabis varieties, chemotypes and phenotypes without considering human selection through breeding (alongside natural processes in the wild, especially with landrace varieties). This is going to be where we find the other answers that are most relevant to your question.