I am trying to understand the proof of KAK decomposition of $SL(2,\mathbb{R})$ from the following text:
I am a bit confused about the rotation around $i$ part. How exactly do we know what amount of stretching needs to be done and after that how do we determine the $U_1$ matrix? A detailed explanation is most welcome. Thanks.

$D_K(i)=Ki$ must be the same (hyperbolic) distance from $i$ that $Ai$ is, so $K=d(i,Ai)$.
The geodesic between $i$ and $Ai$ intersects the imaginary axis at the angle $\theta$ which defines $U_1$, and lies as an arc on a semicircle whose diameter is on the real axis. Say the center of the semicircle is $c\in\mathbb{R}$; you can solve for $c$ by setting the (Euclidean) distance between $c$ and $i$ equal to that of $c$ and $Ai$ (this yields a quadratic equation). Once you have $c$, you can determine the angle $\theta$: drawing the right triangle between $0,i,c$ you see that $\theta=\cot^{-1}c$.