I have founded a solution on this page: link
If the figure does not fit it is allowing a page breake, that is working.
But the one extra line appears after the figure, and I do not know why, and I do not know how to solve thi issue.
Code
\documentclass{article}
\usepackage[margin=2.5cm]{geometry}
\usepackage{graphicx}
\usepackage{wrapfig}
\usepackage{lipsum}
\usepackage{parskip}
\BeforeBeginEnvironment{wrapfigure}{\setlength{\intextsep}{0pt}}
\newsavebox\curwrapfig
\makeatletter
\long\def\wrapfiguresafe#1#2#3{
\sbox\curwrapfig{#3}
\par\penalty-100
\begingroup
\dimen@\pagegoal \advance\dimen@-\pagetotal
\advance\dimen@-\baselineskip
\ifdim \ht\curwrapfig>\dimen@
\break%
\fi%
\endgroup%
\begin{wrapfigure}{#1}{#2}
\usebox\curwrapfig
\end{wrapfigure}
}
\makeatother
\begin{document}
\lipsum[1-6]
\wrapfiguresafe{r}{0mm}{\centering\rule{3cm}{6cm}}
\lipsum[1-6]
\end{document}
Screenshot:


\vfill\hruleto the bottom of the page, you will see that the wrapfigure will overlap the last shortened line of text (text can shrink or expand slightly to fit) – John Kormylo Jan 01 '23 at 18:07