BERLIN – Poland's right-wing president, Andrzej Duda, won a second term by a razor-thin margin in results announced Monday, paving the way for Warsaw to continue a political program that human rights advocates and European leaders have criticized as undermining democracy.

Duda — an ally of President Donald Trump — won 51.2% of the vote in Sunday's runoff election, the electoral commission said after counting 99.97% of the ballots. Centrist Warsaw Mayor Rafal Trzaskowski trailed with 48.8%.

Turnout above 68%, the highest in a presidential election in 25 years, showed how deeply Poles cared about what was seen as a pivotal election.

Analysts said it was less a choice between two candidates than between two Polands: one that clashes with much of the rest of Europe on values and another that aligns with them.

Duda ran a campaign notable for its anti-LGBT rhetoric. He proposed a constitutional amendment that would bar single-sex couples from adopting children and at one point he suggested that efforts to advance gay rights were worse than communism.

Trzaskowski promised a more tolerant Poland.

The election was also a referendum on the country's nationalist ruling party, which backed Duda's campaign.

The Law and Justice party has drawn rebukes from the European Union and human rights groups over the past five years, particularly for its attempts to force out independent judges. The party would have remained in control of Poland's parliament regardless of the outcome of the presidential contest. But because the president can sign or veto new laws, a Trzaskowski win would have presented a stumbling block for the party's agenda.

Analysts say they expect Law and Justice to leverage his win to further their hard-line policies, including an effort to "re-Polandize" the media and bring foreign-owned outlets under Polish control.

"Having Duda in office again, the temptation will be huge to make use of him and his signature," said Piotr Buras, head of the Warsaw office of the European Council on Foreign Relations.

Still, Buras said the close result should be a "warning sign" for the governing party.

Duda is the first to receive more than 10 million votes since 1990, when Nobel Peace Prize laureate Lech Walesa became the country's first democratically elected president. But Trzaskowski's 9.9 million votes are equally stunning, and would have seen him win any other presidential election in the past three decades.

"The division is very deep and the polarization has grown stronger," Buras said, adding that it might complicate efforts to govern. "Those who are politically active are really deeply divided into two halves."