import Mathlib.Analysis.InnerProductSpace.PiL2

open TensorProduct


lemma OrthonormalBasis.sum_repr'
  {𝕜 : Type*} [RCLike 𝕜]
  {E : Type*} [NormedAddCommGroup E] [InnerProductSpace 𝕜 E]
  [Fintype ι]
  (b : OrthonormalBasis ι 𝕜 E)
  (v : E) :
  v = ∑ i, ⟪b i, v⟫_𝕜 • (b i) := by
  nth_rw 1 [← (b.sum_repr v)]
  simp_rw [b.repr_apply_apply v]


noncomputable def InnerProductSpace.canonicalTensor
  (E : Type u_2) [NormedAddCommGroup E] [InnerProductSpace ℝ E] [FiniteDimensional ℝ E] 
  : E ⊗[ℝ] E := by
  let v := stdOrthonormalBasis ℝ E
  exact ∑ i, (v i) ⊗ₜ[ℝ] (v i)


theorem InnerProductSpace.InvariantTensor
  (E : Type*) [NormedAddCommGroup E] [InnerProductSpace ℝ E] [FiniteDimensional ℝ E]
  (v : OrthonormalBasis (Fin (FiniteDimensional.finrank ℝ E)) ℝ E)
  : InnerProductSpace.canonicalTensor E = ∑ i, (v i) ⊗ₜ[ℝ] (v i) := by

  unfold InnerProductSpace.canonicalTensor
  let v₁ := stdOrthonormalBasis ℝ E

  conv =>
    right
    arg 2
    intro i
    rw [v₁.sum_repr' (v i)]
  simp_rw [TensorProduct.sum_tmul, TensorProduct.tmul_sum, TensorProduct.smul_tmul_smul]
  
  conv =>
    right
    rw [Finset.sum_comm]
    arg 2
    intro y
    rw [Finset.sum_comm]
    arg 2
    intro x
    rw [← Finset.sum_smul]
    arg 1
    arg 2
    intro i
    rw [← real_inner_comm (v₁ x)]
  simp_rw [OrthonormalBasis.sum_inner_mul_inner v]

  have {x : Fin (FiniteDimensional.finrank ℝ E)} : ∑ x_1 : Fin (FiniteDimensional.finrank ℝ E), ⟪v₁ x, v₁ x_1⟫_ℝ • v₁ x ⊗ₜ[ℝ] v₁ x_1 = v₁ x ⊗ₜ[ℝ] v₁ x := by
    rw [Fintype.sum_eq_single x, orthonormal_iff_ite.1 v₁.orthonormal]; simp
    intro r₁ hr₁
    rw [orthonormal_iff_ite.1 v₁.orthonormal]; simp; tauto
  simp_rw [this]
