Watch out Accesibility (AA/AAA). Colour contrast by itself is useless. Really different colors can have no contrast at all for colour blind people.
IMHO a calculation for such a color could go like this:
(Use "HLS" for simplicity)
- Rotate Hue 180º to get the (maybe useless) maximal color contrast
- Calculate Brightness Difference.
- ( Calculate Colour Difference... unnecesary, it's maximal or almost )
- Calculate Contrast Ratio.
- If the resulting color complies the requirements calculation ends, if not, loop:
- If Brightness Difference is not enought increase or
decrese calculated color luminosity (L) by a certain amount or ratio (up or
down depending on the original colour brightness: > or < than the mid
value)
- Check if it complies your requirements, if it does calculation ends.
- if luminosity can be increased (or decrased) any more there is no valid color to comply the requirements, just try black and white, take "the best one" of those (probably the one with bigger contrast ratio) and end.