throughout evolution thousands of different genetic "errors" occur called mutations... these mutations can be beneficial, neutral, or harmful... beneficial mutations usually end up becoming universally present in all of that plants lineage...
so let's say you have a cabbage that is born with a genetic mutation that allows it to grow spikes to ward off rodents... obviously this plant will have a better chance of survival and so will the offspring that inherit this same trait... eventually the spiked cabbage becomes the main phenotype (genetic variant) of it's species and the mutation becomes part of what the plant is...
now thc seems like it obviously has SOME benefit to the plant because it is universal among cannabis... my guess is the psychoactive properties of THC may have been toxic to a specific type of insect or pest that was common in the early years of cannabis's existence... there has to be some beneficial property which gives a THC producing plant a reproductive advantage...
so it's either pest control (a la nicotine for tobacco, caffeine for coffee) or it helps gather pollen by forming a stick resin around the pistils.
maybe it attracts bees? it may have some kind of pheromonal effect on honeybees helping them pollinate therefore increasing the survival/reproductive efficiency of the species.
if it wasn't universally beneficial then not every cannabis plant would produce THC, it would be like blue eyes or brown hair, something irrelevant to the survival of the species.
so it's not happenstance, it exists for a reason.
everything exists for a reason.
the reason according to wikipedia:
THC in
Cannabis is assumed to be involved in
self-defense, perhaps against
herbivores.
[6] THC also possesses high
UV-B (280-315 nm) absorption properties and it has been speculated that this could protect the seed buds from harmful UV radiation.[
citation needed]
it's a simple adaptation that causes profound psychoactive effects in mammals notably humans... it really is that simple.