{- | **The `k[X]`-module of a square matrix** (Mines–Richman–Ruitenburg, §V.4).

     A square matrix `A` over a discrete field `k` makes $k^n$ into a module over $k[X]$, with $p \cdot v = p(A) v$
     (`matPolyModule`). Lemma V.4.1 (`matPolyModule-presentation`): the standard basis vectors $e_i$ present this
     module, and the relations are generated by the rows $d_i = X e_i - \sum_j a_{ji} e_j$ of the matrix
     $X \cdot 1 - A^T$ (`presentationMatrix`); moreover these rows are linearly independent over $k[X]$
     (`presentationMatrix-independent`), so the module of relations is free.
-}

\import Algebra.Group
\import Algebra.Group.Product (ArrayAbGroup)
\import Algebra.Group.GroupHom
\import Algebra.Algebra
\import Algebra.Linear.Matrix
\import Algebra.Linear.Matrix.Diagonalizable (mulVec)
\import Algebra.Linear.Matrix.Kronecker (ide-diag, ide-offdiag)
\import Algebra.Linear.Matrix.PolyEval
\import Algebra.Meta
\import Algebra.Module
\import Algebra.Module.Presentation
\import Algebra.Monoid
\import Algebra.Pointed
\import Algebra.Ring
\import Algebra.Ring.Poly
\import Algebra.Ring.Poly.Euclidean
\import Algebra.Semiring
\import Algebra.Field
\import Arith.Nat
\import Data.Array
\import Logic
\import Logic.Meta
\import Order.PartialOrder
\import Paths
\import Paths.Meta
\import Set
\import Set.Fin

-- | $k^n$ as a module over $k[X]$, where `X` acts as `A`.
\func matPolyModule {K : DiscreteField} {n : Nat} (A : Matrix K n n) : LModule (PolyEuclideanDomain K) \cowith
  | AbGroup => ArrayAbGroup n K
  | *c p v => mulVec (matPolyEval p A) v
  | *c-assoc => pmap (mulVec __ _) matPolyEval_* *> mulVec.comp
  | *c-ldistr => mulVec-ldistr
  | *c-rdistr => pmap (mulVec __ _) matPolyEval_+ *> mulVec-rdistr
  | ide_*c => pmap (mulVec __ _) matPolyEval_ide *> mulVec.ide
  \where {
    \lemma mulVec-ldistr {R : Ring} {n m : Nat} {M : Matrix R n m} {u v : Array R m}
      : mulVec M (u + {ArrayLModule m (RingLModule R)} v) = mulVec M u + {ArrayLModule n (RingLModule R)} mulVec M v
      => exts \lam i => pmap R.BigSum (exts \lam j => ldistr) *> R.BigSum_+

    \lemma mulVec-rdistr {R : Ring} {n m : Nat} {M N : Matrix R n m} {v : Array R m}
      : mulVec (M + N) v = mulVec M v + {ArrayLModule n (RingLModule R)} mulVec N v
      => exts \lam i => pmap R.BigSum (exts \lam j => rdistr) *> R.BigSum_+
  }

-- | The standard basis vector $e_i$.
\func stdVec {R : Ring} {n : Nat} (i : Fin n) : Array R n
  => \lam k => MatrixRing.ide {R} {n} k i

-- | $M e_j$ is the `j`-th column of `M`.
\lemma mulVec_stdVec {R : Ring} {n m : Nat} {M : Matrix R n m} {j : Fin m} : mulVec M (stdVec j) = \new Array R n (\lam i => M i j)
  => exts \lam i => R.BigSum-unique j (\lam k jk => pmap (_ *) (ide-offdiag (/=-sym jk)) *> zro_*-right) *> pmap (_ *) ide-diag *> ide-right

-- | A combination of standard basis vectors in `matPolyModule A`.
\lemma matPolyModule-comb {K : DiscreteField} {n : Nat} {A : Matrix K n n} (r : Array (Poly K) n)
  : LModule.BigSum {matPolyModule A} (\lam j => r j *c {matPolyModule A} stdVec j) = \new Array K n (\lam i => K.BigSum (\lam j => matPolyEval (r j) A i j))
  => exts \lam i => ArrayLModule.BigSum-index {K} {n} {RingLModule K} *> pmap K.BigSum (exts \lam j => path (\lam t => mulVec_stdVec {K} {n} {n} {matPolyEval (r j) A} {j} t i))

-- | The matrix $X \cdot 1 - A^T$ over $k[X]$; its rows are the relations $X e_i - \sum_j a_{ji} e_j$.
\func presentationMatrix {K : DiscreteField} {n : Nat} (A : Matrix K n n) : Matrix (Poly K) n n
  => mkMatrix \lam i j => padd 1 0 * {PolyRing K} MatrixRing.ide {PolyRing K} {n} i j - {PolyRing K} padd 0 (A j i)

{- | **Lemma V.4.1.** The standard basis vectors present the `k[X]`-module `matPolyModule A`, with presentation
     matrix $X \cdot 1 - A^T$. -}
\lemma matPolyModule-presentation {K : DiscreteField} {n : Nat} (A : Matrix K n n)
  : IsPresentation {PolyEuclideanDomain K} {matPolyModule A} stdVec (presentationMatrix A)
  => (\lam v => inP (\lam j => padd 0 (v j), inv (const-comb A v)),
      \lam r => (\lam rel => \case reduce A r \with {
                   | inP (s, b, rb) => inP (s, exts \lam j => rb j *> pmap (_ +) (pmap (padd 0) (const-zero A r s b rb rel j) *> peq) *> zro-right)
                 },
                 \lam (inP (s, rs)) => pmap (\lam (r' : Array (Poly K) n) => LModule.BigSum {matPolyModule A} (\lam j => r' j *c {matPolyModule A} stdVec j)) rs
                    *> rowComb-relation A s))
  \where {
    -- | Constant polynomials act by scalars, so a constant row combines the standard basis to itself.
    \lemma const-comb {K : DiscreteField} {n : Nat} (A : Matrix K n n) (b : Array K n)
      : LModule.BigSum {matPolyModule A} (\lam j => padd 0 (b j) *c {matPolyModule A} stdVec j) = b
      => matPolyModule-comb (\lam j => padd 0 (b j)) *> arrayExt \lam i =>
           pmap K.BigSum (arrayExt \lam j => pmap (`+ _) (K.BigSum_zro \lam _ => zro_*-left) *> zro-left)
             *> K.BigSum-unique {\lam j => b j * MatrixRing.ide {K} {n} i j} i (\lam j ij => pmap (b j *) (ide-offdiag ij) *> zro_*-right)
             *> pmap (b i *) (ide-diag {K} {n} {i}) *> ide-right

    -- | Combinations of the rows of the presentation matrix are relations.
    \lemma rowComb-relation {K : DiscreteField} {n : Nat} (A : Matrix K n n) (s : Array (Poly K) n)
      : LModule.BigSum {matPolyModule A} (\lam j => rowComb s (presentationMatrix A) j *c {matPolyModule A} stdVec j) = LModule.zro {matPolyModule A}
      => inv (rowComb.comb {PolyEuclideanDomain K} {matPolyModule A} s (presentationMatrix A) stdVec)
           *> LModule.BigSum_zro {matPolyModule A} (\lam i => pmap (s i *c {matPolyModule A}) (row-relation A i) *> LModule.*c_zro-right {matPolyModule A})

    -- | If a relation is a combination of the rows plus a constant row, the constant row is zero.
    \lemma const-zero {K : DiscreteField} {n : Nat} (A : Matrix K n n) (r s : Array (Poly K) n) (b : Array K n)
      (rb : \Pi (j : Fin n) -> r j = rowComb s (presentationMatrix A) j + padd 0 (b j))
      (rel : LModule.BigSum {matPolyModule A} (\lam j => r j *c {matPolyModule A} stdVec j) = LModule.zro {matPolyModule A}) (j : Fin n) : b j = 0
      => \have | sum-eq : LModule.BigSum {matPolyModule A} (\lam j => r j *c {matPolyModule A} stdVec j)
                         = LModule.BigSum {matPolyModule A} (\lam j => rowComb s (presentationMatrix A) j *c {matPolyModule A} stdVec j)
                           + {matPolyModule A} LModule.BigSum {matPolyModule A} (\lam j => padd 0 (b j) *c {matPolyModule A} stdVec j)
                   => pmap (LModule.BigSum {matPolyModule A}) (arrayExt \lam j => pmap (`*c {matPolyModule A} stdVec j) (rb j) *> LModule.*c-rdistr {matPolyModule A} {rowComb s (presentationMatrix A) j} {padd 0 (b j)} {stdVec j}) *> LModule.BigSum_+ {matPolyModule A}
                | e : b = LModule.zro {matPolyModule A} => inv (const-comb A b) *> inv (zro-left {matPolyModule A}) *> pmap (`+ {matPolyModule A} _) (inv (rowComb-relation A s)) *> inv sum-eq *> rel
         \in pmap (\lam (v : Array K n) => v j) e

    -- | The rows of the presentation matrix are relations.
    \lemma row-relation {K : DiscreteField} {n : Nat} (A : Matrix K n n) (i : Fin n)
      : LModule.BigSum {matPolyModule A} (\lam j => presentationMatrix A i j *c {matPolyModule A} stdVec j) = LModule.zro {matPolyModule A}
      => matPolyModule-comb (presentationMatrix A i) *> arrayExt \lam k => step k
      \where
        \lemma step {K : DiscreteField} {n : Nat} {A : Matrix K n n} {i : Fin n} (k : Fin n)
          : K.BigSum (\lam j => matPolyEval (presentationMatrix A i j) A k j) = 0
          => pmap K.BigSum (arrayExt {K} {n} {\new Array K n (\lam j => matPolyEval (presentationMatrix A i j) A k j)} \lam j => entry A i j k j)
           *> AbGroup.BigSum_- {K} {n} {\lam j => MatrixRing.ide {K} {n} i j * A k j} {\lam j => A j i * MatrixRing.ide {K} {n} k j}
           *> pmap2 (-) (K.BigSum-unique {\lam j => MatrixRing.ide {K} {n} i j * A k j} i (\lam j ij => pmap (`* A k j) (ide-offdiag ij) *> K.zro_*-left) *> pmap (`* A k i) (ide-diag {K} {n} {i}) *> K.ide-left)
                        (K.BigSum-unique {\lam j => A j i * MatrixRing.ide {K} {n} k j} k (\lam j kj => pmap (A j i *) (ide-offdiag kj) *> K.zro_*-right) *> pmap (A k i *) (ide-diag {K} {n} {k}) *> K.ide-right) *> negative-right

    -- | Every row over `k[X]` is a combination of the rows of the presentation matrix plus a constant row.
    \lemma reduce {K : DiscreteField} {n : Nat} (A : Matrix K n n) (r : Array (Poly K) n)
      : ∃ (s : Array (Poly K) n) (b : Array K n) (\Pi (j : Fin n) -> r j = rowComb s (presentationMatrix A) j + padd 0 (b j))
      => \case uniform-degree r \with {
        | inP (N, dr) => reduce-deg A N r dr
      }

    \lemma uniform-degree {R : AddPointed} {n : Nat} (r : Array (Poly R) n) : ∃ (N : Nat) (\Pi (j : Fin n) -> degree< (r j) N) \elim n, r
      | 0, nil => inP (0, \case __)
      | suc n, p :: r => \case degree<-exists p, uniform-degree r \with {
        | inP (N, dp), inP (M, dr) => inP (N + M, \case \elim __ \with {
          | 0 => degree<-mono dp (NatSemiring.<=_+ <=-refl zero<=_)
          | suc j => degree<-mono (dr j) (transport (`<= _) zro-left (NatSemiring.<=_+ zero<=_ <=-refl))
        })
      }

    \lemma rowComb-add {R : Ring} {m n : Nat} (u v : Array R m) (B : Matrix R m n) (j : Fin n)
      : rowComb (\lam i => u i + v i) B j = rowComb u B j + rowComb v B j
      => pmap R.BigSum (exts \lam i => rdistr) *> R.BigSum_+

    -- | Combining the rows of the presentation matrix: $\sum_i q_i d_{ij} = q_j X - \sum_i q_i a_{ji}$.
    \lemma row-q {K : DiscreteField} {n : Nat} (A : Matrix K n n) (q : Array (Poly K) n) (j : Fin n)
      : rowComb q (presentationMatrix A) j = q j * padd 1 0 - AddMonoid.BigSum (\lam i => q i * padd pzero (A j i))
      => pmap (AddMonoid.BigSum {PolyRing K}) (exts \lam i => (ldistr *> pmap (_ +) (Ring.negative_*-right {PolyRing K})
              : q i * presentationMatrix A i j = q i * (padd 1 0 * MatrixRing.ide {PolyRing K} {n} i j) - q i * padd pzero (A j i))) *> AbGroup.BigSum_- {PolyRing K} {n} {\lam i => q i * (padd 1 0 * MatrixRing.ide {PolyRing K} {n} i j)} {\lam i => q i * padd pzero (A j i)}
           *> pmap (`- _) (AddMonoid.BigSum-unique {PolyRing K} {\lam i => q i * (padd 1 0 * MatrixRing.ide {PolyRing K} {n} i j)} j
                              (\lam i ji => pmap (q i *) (pmap (padd 1 0 *) (ide-offdiag (/=-sym ji)) *> Semiring.zro_*-right {PolyRing K} {padd 1 0}) *> Semiring.zro_*-right {PolyRing K} {q i})
                             *> pmap (q j *) (pmap (padd 1 0 *) (ide-diag {PolyRing K} {n} {j}) *> ide-right))

    \lemma alg {G : AbGroup} {x s b c : G} : x - (s + b) + s + (b + c) = x + c
      => equation.abGroup

    \lemma degree<_*const {R : Ring} {a : R} {p : Poly R} {N : Nat} (d : degree< p N) : degree< (p * {PolyRing R} padd pzero a) N
      => \lam s => polyCoef_*-right *> pmap (`* a) (d s) *> R.zro_*-left

    \lemma degree<-mono {R : AddPointed} {p : Poly R} {N M : Nat} (d : degree< p N) (q : N <= M) : degree< p M
      => \lam s => d (q <=∘ s)

    \lemma degree<_BigSum {R : Ring} {N : Nat} (l : Array (Poly R)) (d : \Pi (j : Fin l.len) -> degree< (l j) N) : degree< (AddMonoid.BigSum {PolyRing R} l) N \elim l
      | nil => \lam _ => idp
      | p :: l => degree<_+ (d 0) (degree<_BigSum l \lam j => d (suc j))

    \lemma shift-eq {R : AddPointed} (p : Poly R) : padd (polyShift p) (polyCoef p 0) = p \elim p
      | pzero => peq
      | padd p e => idp

    \lemma polyCoef_shift {R : AddPointed} (p : Poly R) (k : Nat) : polyCoef (polyShift p) k = polyCoef p (suc k) \elim p
      | pzero => idp
      | padd p e => idp

    \lemma reduce-deg {K : DiscreteField} {n : Nat} (A : Matrix K n n) (N : Nat) (r : Array (Poly K) n) (dr : \Pi (j : Fin n) -> degree< (r j) N)
      : ∃ (s : Array (Poly K) n) (b : Array K n) (\Pi (j : Fin n) -> r j = rowComb s (presentationMatrix A) j + padd 0 (b j)) \elim N
      | 0 => inP (\lam _ => 0, \lam _ => 0, \lam j => degree<0 (dr j) *> inv (pmap2 (+) (AddMonoid.BigSum_zro \lam i => Semiring.zro_*-left {PolyRing K} {presentationMatrix A i j}) peq *> zro-left))
      | suc N =>
        \let | q j => polyShift (r j)
             | rr j => AddMonoid.BigSum (\lam i => q i * padd pzero (A j i))
             | drr (j : Fin n) : degree< (rr j) N => degree<_BigSum _ \lam i => degree<_*const \lam s => polyCoef_shift (r i) _ *> dr i (suc<=suc s)
             | (inP (s1, b1, rbb)) => reduce-deg A N rr drr
        \in inP (\lam j => q j + s1 j, \lam j => b1 j + polyCoef (r j) 0, \lam j =>
              \have | e1 : rowComb (\lam i => q i + s1 i) (presentationMatrix A) j = q j * padd 1 0 - rr j + rowComb s1 (presentationMatrix A) j
                         => rowComb-add q s1 (presentationMatrix A) j *> pmap (`+ _) (row-q A q j)
                     | e2 : padd 0 (b1 j + polyCoef (r j) 0) = padd 0 (b1 j) + padd 0 (polyCoef (r j) 0)
                         => (polyHom {K}).func-+
              \in inv (shift-eq (r j)) *> padd-expand *> inv (pmap2 (+) e1 e2 *> pmap (\lam z => q j * padd 1 0 - z + _ + (padd 0 (b1 j) + _)) (rbb j) *> alg))

    \lemma ide-eq {R : Ring} {n : Nat} {i j : Fin n} (p : i = j) : MatrixRing.ide {R} {n} i j = 1
      => transportInv (\lam x => MatrixRing.ide {R} {n} x j = 1) p ide-diag

    \lemma eval-form {K : DiscreteField} {n : Nat} {A : Matrix K n n} {e : Poly K} {a : K}
      : matPolyEval (padd 1 0 * {PolyRing K} e - {PolyRing K} padd 0 a) A = A * matPolyEval e A - CAlgebra.coefHom {MatrixAlgebra K n} a
      => matPolyEval_+ {K} {n} {padd 1 0 * {PolyRing K} e} {negative (padd 0 a)} {A} *> pmap2 (+) (matPolyEval_* {K} {n} {padd 1 0} {e} {A} *> pmap (`* _) (matPolyEval_X {K} {n} {A}))
           (AddGroupHom.func-negative {matPolyEvalHom A} {padd 0 a} *> pmap negative (matPolyEval_const {K} {n} {a} {A}))

    \lemma entry {K : DiscreteField} {n : Nat} (A : Matrix K n n) (i j k l : Fin n)
      : matPolyEval (presentationMatrix A i j) A k l = MatrixRing.ide {K} {n} i j * A k l - A j i * MatrixRing.ide {K} {n} k l
      => \let C => CAlgebra.coefHom {MatrixAlgebra K n} (A j i)
         \in path (\lam t => eval-form {K} {n} {A} {MatrixRing.ide {PolyRing K} {n} i j} {A j i} t k l) *> \case decideEq i j \with {
           | yes p => pmap (\lam M => (A * M - C) k l) (pmap (matPolyEval __ A) (ide-eq p) *> matPolyEval_ide) *> pmap (\lam M => (M - C) k l) ide-right
                        *> pmap (`- _) (inv ide-left *> pmap (`* _) (inv (ide-eq p)))
           | no q => pmap (\lam M => (A * M - C) k l) (pmap (matPolyEval __ A) (ide-offdiag q) *> (matPolyEvalHom A).func-zro) *> pmap (\lam M => (M - C) k l) zro_*-right
                       *> pmap (`- _) (inv zro_*-left *> pmap (`* _) (inv (ide-offdiag q)))
         }
  }

-- | **Lemma V.4.1, freeness.** The rows of $X \cdot 1 - A^T$ are linearly independent over `k[X]`.
\lemma presentationMatrix-independent {K : DiscreteField} {n : Nat} (A : Matrix K n n) (h : Array (Poly K) n)
  (rel : rowComb h (presentationMatrix A) = 0) (i : Fin n) : h i = 0
  => \case matPolyModule-presentation.uniform-degree h \with {
    | inP (N, dh) => degree<0 \lam {k} _ => coef-zero rel N dh N k (transport (N <=) NatSemiring.+-comm (NatSemiring.<=_+ <=-refl zero<=_)) i
  }
  \where {
    -- | The coefficient recursion: $c_m(j) = \sum_i a_{ji} c_{m+1}(i)$, where $c_m(j)$ is the `m`-th coefficient of $h_j$.
    \lemma coef-rec {K : DiscreteField} {n : Nat} {A : Matrix K n n} {h : Array (Poly K) n} (rel : rowComb h (presentationMatrix A) = 0) (m : Nat) (j : Fin n)
      : polyCoef (h j) m = K.BigSum (\lam i => polyCoef (h i) (suc m) * A j i)
      => \have | e : h j * padd 1 0 = AddMonoid.BigSum (\lam i => h i * padd pzero (A j i))
                   => AddGroup.fromZero (inv (matPolyModule-presentation.row-q A h j) *> pmap (\lam (v : Array (Poly K) n) => v j) rel)
               | lhs : polyCoef (h j * padd 1 0) (suc m) = polyCoef (h j) m
                   => pmap (polyCoef __ (suc m)) *-comm *> polyCoef-linear-* (h j) 1 0 m *> pmap2 (+) (pmap (polyCoef __ m) ide-left) zro_*-left *> zro-right
         \in inv lhs *> pmap (polyCoef __ (suc m)) e *> polyCoef_BigSum *> pmap K.BigSum (arrayExt {K} {n} {map (polyCoef __ (suc m)) (\new Array (Poly K) n (\lam i => h i * padd pzero (A j i)))} {\new Array K n (\lam i => polyCoef (h i) (suc m) * A j i)} \lam i => polyCoef_*-right)

    -- | Downward induction: all coefficients vanish.
    \lemma coef-zero {K : DiscreteField} {n : Nat} {A : Matrix K n n} {h : Array (Poly K) n} (rel : rowComb h (presentationMatrix A) = 0)
      (N : Nat) (dh : \Pi (j : Fin n) -> degree< (h j) N) (t m : Nat) (q : N <= m + t) (j : Fin n) : polyCoef (h j) m = 0 \elim t
      | 0 => dh j q
      | suc t => coef-rec rel m j *> K.BigSum_zro {\new Array K n (\lam i => polyCoef (h i) (suc m) * A j i)} (\lam i => pmap (`* _) (coef-zero rel N dh t (suc m) (transport (N <=) (pmap suc NatSemiring.+-comm *> NatSemiring.+-comm {t} {suc m}) q) i) *> zro_*-left)
  }