/-- **Fermat's two-squares theorem, by Zagier's proof, with every step reconstructed.** If `p` is
prime and `p ≡ 1 (mod 4)`, then `p = a² + b²`. Since `|S|` is odd, the involution
`(x, y, z) ↦ (x, z, y)` of `S` also has a fixed point `(x, y, y)`, and then
`p = x² + 4y² = x² + (2y)²`. -/
theorem zagier_two_squares {p : ℕ} (hp : p.Prime) (h4 : p % 4 = 1) :
∃ a b : ℕ, a ^ 2 + b ^ 2 = p := by
have swap_mem : ∀ t ∈ zagierSet p, ((t.1, t.2.2, t.2.1) : ℕ × ℕ × ℕ) ∈ zagierSet p := by
intro t ht
rw [mem_zagierSet hp] at ht ⊢
simp only
rw [← ht]; ring
let g : Function.End (zagierSet p) := fun t => ⟨(t.1.1, t.1.2.2, t.1.2.1), swap_mem _ t.2⟩
have hg : g ^ 2 ^ 1 = 1 := by
funext t
exact Subtype.ext rfl
have hmod := Equiv.Perm.card_fixedPoints_modEq (p := 2) (n := 1) hg
have hodd := card_odd hp h4
have hpos : 0 < Fintype.card (Function.fixedPoints g) := by
have : Fintype.card (Function.fixedPoints g) % 2 = 1 := by
rw [← hodd]; exact hmod.symm
omega
obtain ⟨⟨⟨⟨x, y, z⟩, hmem⟩, hfix⟩⟩ := Fintype.card_pos_iff.1 hpos
have hyz : z = y := by
have := congrArg (fun t => t.1.2.1) hfix
simpa [g] using this
rw [mem_zagierSet hp] at hmem
simp only at hmem
subst hyz
exact ⟨x, 2 * z, by rw [← hmem]; ring⟩