Plants produce different classes of secondary metabolites to achieve explicit ecological effects. Regardless of type, the chemical mechanics of metabolite production are selfsame: attach specific elements onto carbon rings.
The issue is determining which molecules might be efficacious for a precise effect. In retrospect, the ecology of effective interaction in secondary metabolites looks obvious. But hindsight brings only bewilderment when considering how plants knew which formulas to concoct.
Metabolite creation was not a trial-and-error exercise. It instead arose, as does adaption, from goal orientation.
Producing sugary fruits to attract seed carriers seems simple enough, but plants package seeds specifically to target consumers that will eat and disperse them. Part of the packaging plan includes skins that facilitate the intended aim of maximizing reproduction potential. A further detail is having the skins advertise their conditions, so that fruits are not eaten before the plant is ready for them to go to market. These are non-trivial decisions. Failure to anticipate can mean wasted potential and loss of life.
Constructing noxious metabolites is an entirely different challenge. Warding off herbivores involves knowing what is seriously unpalatable to those that pose the greatest threat.
Plants produce molecules that mimic the hormones which control animal reproduction and development. They package these poisonous parcels in precise places where a threat may arise: leaves, stems, and/or roots.
Insects follow one of 2 development plans. Plants know the key to both and produce specific hormones that deter development.
Chemical deterrents that alter the life cycle put a profound hex on an herbivore; a legacy that affects a predator population over a considerable expanse of time.
Those same metabolites which keep herbivores at bay become medicines for animals which are plagued with the same problem: being chewed on by little critters. Even with rise of synthetic drugs in the late 20th century, 2/3rds of new remedies still come from the secondary metabolites of plants.