In page 179 of Altland and Simon, Condensed Matter Field Theory, the author obtained the action
\begin{equation} S[\theta]=\frac{1}{2\pi}\int dx\,d\tau\,\left[(\partial_x\theta)^2+(\partial_\tau\theta)^2\right] \tag{4.48b} \end{equation}
The author then obtained the canonical momentum corresponding to $\theta$ as
$$\pi_\theta=\partial_{\partial_\tau \theta}\mathcal{L}=\partial_\tau\theta/\pi.\tag{4.48c}$$
According to Hamiltonian mechanics,
\begin{equation} \mathcal{H}=\dot{q}\frac{\partial\mathcal{L}}{\partial\dot{q}}-\mathcal{L}=\dot{q}p-\mathcal{L} \end{equation}
taking $\theta\leftrightarrow q$ and making use of $\partial_\tau\theta=\pi\pi_\theta$, we should have \begin{align} \mathcal{H}&=(\partial_\tau\theta)\pi_\theta-\frac{1}{2\pi}\left[(\partial_x\theta)^2+(\partial_\tau\theta)^2\right]\\ &=\frac{1}{2\pi}\left[\pi^2\pi_\theta^2-(\partial_x\theta)^2\right]. \end{align}
However, this expression is different from the Hamiltonian density given in the textbook $$\mathcal{H}=\frac{1}{2\pi}\left[(\partial_x\theta)^2+\pi^2\pi_\theta^2\right].\tag{4.48d}$$ What did I do wrong here? How to obtain the Hamiltonian given in the textbook? And also how to obtain the new action
\begin{equation} S[\theta,\pi_\theta]=\frac{1}{2}\int dx\,d\tau\,\left(\frac{1}{\pi}(\partial_x\theta)^2 +\pi\pi_\theta^2 +2i\partial_\tau\theta\pi_\theta\right)~?\tag{4.48e} \end{equation}
In particular, where is the last term in the parenthesis $2i\partial_\tau\theta\pi_\theta$ coming from?