A gay father has won custody of his 3-year-old son after a bitter and emotional court battle in Manhattan against the toddler’s surrogate mother.

The child’s mother was denied custody in a decision by State Supreme Court Justice Marylin Diamond, which was made public yesterday.

The judge found it was in the boy’s “best interests” to stay with his father, with whom he already lives. And while the child’s mom won some visitation rights, she also has to pay child support.

Her lawyer, Lindsay Feiberg, said she’ll appeal.

Surrogate-parenting contracts are illegal in New York – so the judge ruled she would not enforce a letter agreement between the father, identified in the court decision as G, and the mother, identified as C.

But Diamond decided that the letter, written by the mother, gave some clues to what the parents planned and how to shape her decision.

The odd tale began in 1996, when the mom, then 43 and the owner of a graphic-design company, offered to bear the child of the father, one of her employees.

In the letter sent to the father, she agreed he and his domestic partner would take the child home from the hospital and adopt him after “a respectable period of time.” The father agreed not to seek child-support money from the mom, while the mother agreed to “not meddle in the baby’s rearing.”

The dad also agreed to pay the mom $30,000 for bearing his child, but the court papers say he paid only $3,000 in the illegal deal.

After the baby was born, the mother decided she wanted more time with her son, which led to the ugly court fight.

At one point, an expert testifying for the mom argued that the boy was “manifesting signs of gender confusion due to G.’s parenting.” But two independent court experts told the judge that wasn’t the case – and that the father was the better parent for the boy.

Diamond agreed, noting that the child has been with his dad since birth and that the mom hadn’t even bought a crib for her apartment until after going to court.