Elliptic Curve Digital Signature algorithm fails
In the question, $p$ designates the modulus of the base field $\mathbb Z_p$, as confirmed by the fact that for  $p=977$ and the curve $y^2\equiv x^3+x+1\pmod p$, it holds that $19\times(0,1)=(396,650)$ and $17\times(0,1)=(699,739)$.
Problem is, in other steps, the question reduces $r$, $s$ and related quantities modulo that same $p$, rather than modulo the order $n$ of the group generated by $G$. That's more than enough to cause the observed failure.
As an aside, the ECDSA specification requires that $n$ is prime . In the question, the curve and $G$ is such that $n=987=3\cdot7\cdot47$ is composite. One consequence is that nearly half the choices of $\text{random key}$ are invalid, and I'm uncertain about if it otherwise makes some signature unverifiable. We do not care about the possible security implications since $p$ is so small as to make the whole thing insecure anyway.
I suggest $p=1033$, which will give a prime $n=1061$.