\import Algebra.Group
\import Algebra.Group.GroupHom
\import Algebra.Meta
\import Algebra.Monoid
\import Algebra.Monoid.MonoidHom
\import Algebra.Monoid.SubMonoid
\import Algebra.Pointed
\import Algebra.Pointed.SubPointed
\import Arith.Nat
\import Function
\import Function.Iterate
\import Function.Meta
\import Logic
\import Logic.Meta
\import Meta
\import Order.Lattice
\import Order.PartialOrder
\import Paths
\import Paths.Meta
\import Relation.Equivalence
\import Set.Fin.Instances
\import Set.Set
\open Group \hiding (Dec)

\class SubGroup \extends SubMonoid {
  \override S : Group
  | contains_inverse {x : S} : contains x -> contains (inverse x)

  \func equivalence : Equivalence S \cowith
    | ~ x y => contains (inverse x * y)
    | ~-reflexive => transportInv contains inverse-left contains_ide
    | ~-symmetric c => transport contains (inverse_* *> pmap (_ *) inverse-isInv) (contains_inverse c)
    | ~-transitive {x} {y} c1 c2 => rewriteEq (inverse-right {S} {y}, ide-left) in contains_* c1 c2

  \func Cosets => Quotient (equivalence.~)

  \func inc~ (x : S) : Cosets
    => in~ x

  \lemma contains_~ {x : S} : contains x <-> 1 equivalence.~ x
    => (transportInv contains $ pmap (* x) inverse_ide *> ide-left,
        transport contains $ pmap (* x) inverse_ide *> ide-left)

  \lemma ~-pequiv-left {x y : S} (p : 1 equivalence.~ y) : inc~ x = inc~ (x * y)
    => ~-pequiv $ transport contains (inv (pmap (* y) inverse-left *> ide-left) *> *-assoc) (contains_~.2 p)
} \where {
  {- | The subgroup generated by a subset `S`.
       It is the union of stages: stage 0 is `S`, and each step {closure.apl} adds the unit, products and
       inverses of elements of the previous stage. By {closure.univ}, it is the smallest subgroup containing `S`. -}
  \func closure {G : Group} (S : Set G) : SubGroup G \cowith
    | contains x => ∃ (n : Nat) (iterr apl n S x)
    | contains_ide => inP (1, inP (1, idp))
    | contains_* {x} {y} (inP (n,xr)) (inP (m,yr)) => inP (suc (n ∨ m), inP (2, inP (x, y, apl-inc join-left x xr, apl-inc join-right y yr, idp)))
    | contains_inverse {x} (inP (n,xr)) => inP (suc n, inP (3, inP (x, xr, idp)))
    \where {
      {- | Every element of `S` lies in the subgroup it generates. -}
      \lemma superset {G : Group} (S : Set G) : S ⊆ closure S
        => \lam x<-S => inP (0, x<-S)

      {- | The generated subgroup is contained in every subgroup containing `S`. -}
      \lemma univ (H : SubGroup G) (p : S ⊆ H) (x : G) (q : closure S x) : H x \elim q
        | inP (0, x<-S) => p x<-S
        | inP (suc n, inP (0, x<-C)) => univ H p x (inP (n, x<-C))
        | inP (suc n, inP (1, x=1)) => transport H (inv x=1) H.contains_ide
        | inP (suc n, inP (2, inP (y, z, y<-C, z<-C, x=y*z))) => transport H (inv x=y*z) (H.contains_* (univ H p y (inP (n, y<-C))) (univ H p z (inP (n, z<-C))))
        | inP (suc n, inP (3, inP (y, y<-C, x=inv-y))) => transport H (inv x=inv-y) (H.contains_inverse (univ H p y (inP (n, y<-C))))

      {- | {closure} is monotone. -}
      \lemma mono {G : Group} {S S' : Set G} (p : S ⊆ S') (x : G) (q : closure S x) : closure S' x
        => univ {G} {S} (closure S') (\lam y<-S => superset S' (p y<-S)) x q

      {- | The subgroup generated by a subgroup is the subgroup itself. -}
      \lemma idemp {G : Group} (H : SubGroup G) : closure {G} H = H
        => <=-antisymmetric {SubGroupPoset} {closure {G} H} {H}
             (\lam {x} q => univ {G} {H} H (\lam c => c) x q)
             (superset H)

      {- | If `S` is closed under conjugation, so is the subgroup it generates. -}
      \lemma contains_conjugate (n : \Pi (g x : G) -> S x -> S (conjugate g x)) (g x : G) (q : closure S x)
        : closure S (conjugate g x)
        => univ {G} {S} (PreimageGroup (conjugateHom g) (closure S))
            (\lam {y} y<-S => superset S (n g y y<-S)) x q

      {- | One stage of {closure}: an element of `S`, the unit, a product of two elements of `S`,
           or the inverse of an element of `S`. Since `S` itself is included, the stages increase. -}
      \func apl {G : Group} (S : Set G) : Set G
        => \lam x => OneOf (S x, x = 1, ∃ (y z : G) (S y) (S z) (x = y * z), ∃ (y : G) (S y) (x = inverse y))

      {- | Each stage of {closure} is contained in every later stage. -}
      \lemma apl-inc {n m : Nat} (q : n <= m) (x : G) (p : iterr apl n S x) : iterr apl m S x
        => rewriteI (<=_exists q) (alt n (m -' n) x p)
        \where
          {- | Stage `n` is contained in stage `n + m`. -}
          \lemma alt (n m : Nat) (x : G) (p : iterr apl n S x) : iterr apl (n + m) S x \elim m
            | 0 => p
            | suc m => inP (0, alt n m x p)
    }

  {- | The subgroup generated by a family of elements. -}
  \func generatedBy {G : Group} {J : \Type} (g : J -> G) : SubGroup G
    => closure \lam x => ∃ (j : J) (g j = x)
}

\instance IGroup (S : SubGroup {}) : Group
  | Monoid => IMonoid S
  | inverse x => (inverse x.1, contains_inverse x.2)
  | inverse-left => ext inverse-left
  | inverse-right => ext inverse-right
  \where
    \func embed : GroupHom (IGroup S) S.S \cowith
      | MonoidHom => IMonoid.embed

\instance ICGroup {G : CGroup} (S : SubGroup G) : CGroup
  | Group => IGroup S
  | *-comm => ext *-comm

\class DecSubGroup \extends SubGroup, DecSubMonoid {
  \override S : Group
}

\class NormalSubGroup \extends SubGroup {
  | isNormal (g : S) {h : S} : contains h -> contains (conjugate g h)

  \lemma isNormal' (g : S) {h : S} (c : contains h) : contains (inverse g * h * g)
    => simplify in isNormal (inverse g) c

  \func Quot : Group Cosets \cowith
    | ide => in~ 1
    | * (x y : Cosets) : Cosets \with {
      | in~ g, in~ g' => in~ (g Group.* g')
      | in~ g, ~-equiv x y r => ~-pequiv $ transport contains equation.group r
      | ~-equiv x y r, in~ g => ~-pequiv $ transportInv contains equation.group (isNormal' g r)
    }
    | ide-left {x} => cases x \with {
      | in~ a => pmap in~ ide-left
    }
    | ide-right {x} => cases x \with {
      | in~ a => pmap in~ ide-right
    }
    | *-assoc {x} {y} {z} => cases (x,y,z) \with {
      | in~ x, in~ y, in~ z => pmap in~ *-assoc
    }
    | inverse (x : Cosets) : Cosets \with {
      | in~ g => in~ (Group.inverse g)
      | ~-equiv x y r => ~-pequiv $ transport contains equation.group $ isNormal x (contains_inverse r)
    }
    | inverse-left {x} => cases x \with {
      | in~ a => pmap in~ inverse-left
    }
    | inverse-right {x} => cases x \with {
      | in~ a => pmap in~ inverse-right
    }

  \func quotHom : GroupHom S Quot \cowith
    | func => inc~
    | func-ide => idp
    | func-* => idp

  {- | {quotHom} is surjective. -}
  \lemma quotHom-surj : IsSurj quotHom
    => \lam (in~ x) => inP (x, idp)

  {- | {quotHom} sends every element of the subgroup to the unit. -}
  \lemma quotHom_=1 {x : S} (c : contains x) : quotHom x = ide {Quot}
    => inv $ ~-pequiv $ contains_~.1 c

  {- | Elements $x$ and $y$ have the same image in the quotient when $x y^{ -1}$ lies in the subgroup. -}
  \lemma quotHom-eq {x y : S} (c : contains (x * inverse y)) : quotHom x = quotHom y
    => ~-pequiv $ transport contains equation.group $ isNormal (inverse y) (contains_inverse c)

  {- | The universal property of the quotient: a homomorphism that sends the subgroup to the unit
       factors through {Quot}. -}
  \func quot-univ {K : Group} (f : GroupHom S K) (p : \Pi (x : S) -> contains x -> f x = 1) : GroupHom Quot K \cowith
    | func (x : Quot) : K \with {
      | in~ g => f g
      | ~-equiv g g' r => (K.makeInv (inverse (f g))).inv-cancel-left $
          inverse-left *> inv (p _ r) *> f.func-* *> pmap (* _) f.func-inverse
    }
    | func-* {in~ x} {in~ y} => f.func-*

  {- | The factorization given by {quot-univ} composed with {quotHom} is the original homomorphism. -}
  \lemma quot-univ-beta {K : Group} {f : GroupHom S K} {p : \Pi (x : S) -> contains x -> f x = 1}
    : quot-univ f p GroupHom.∘ quotHom = f
    => exts \lam _ => idp

  {- | Homomorphisms out of the quotient are determined by their values on the image of {quotHom}. -}
  \lemma quot-hom-ext {K : Group} {f g : GroupHom Quot K} (p : \Pi (x : S) -> f (quotHom x) = g (quotHom x))
    : f = g
    => exts \lam (in~ x) => p x
} \where {
  {- | The set of all conjugates $g y g^{ -1}$ of elements $y$ of `S`. -}
  \func conjugates {G : Group} (S : Set G) : Set G
    => \lam x => ∃ (g y : G) (S y) (conjugate g y = x)
    \where {
      {- | Every element of `S` is a conjugate of itself. -}
      \lemma ext {G : Group} (S : Set G) : S ⊆ conjugates S
        => \lam {x} x<-S => inP (1, x, x<-S, conjugate-via-id)

      {- | The set of conjugates is closed under conjugation. -}
      \lemma contains_conjugate {G : Group} {S : Set G} (g x : G) (q : conjugates S x) : conjugates S (conjugate g x)
        => \let (inP (a, y, y<-S, c)) => q
           \in inP (g * a, y, y<-S, equation.group *> pmap (conjugate g) c)
    }

  {- | The normal subgroup generated by a subset: the subgroup generated by the conjugates of its elements. -}
  \func normalClosure {G : Group} (S : Set G) : NormalSubGroup G \cowith
    | SubGroup => SubGroup.closure (conjugates S)
    | isNormal g {h} q => SubGroup.closure.contains_conjugate conjugates.contains_conjugate g h q
    \where {
      {- | Every element of `S` lies in its normal closure. -}
      \lemma superset {G : Group} (S : Set G) : S ⊆ normalClosure S
        => \lam x<-S => SubGroup.closure.superset (conjugates S) (conjugates.ext S x<-S)

      {- | The normal closure is contained in every normal subgroup containing `S`. -}
      \lemma univ (H : NormalSubGroup G) (p : S ⊆ H) (x : G) (q : normalClosure S x) : H x
        => SubGroup.closure.univ {G} {conjugates S} H
             (\lam (inP (a, z, z<-S, c)) => transport H c (H.isNormal a (p z<-S))) x q

      {- | {normalClosure} is monotone. -}
      \lemma mono {G : Group} {S S' : Set G} (p : S ⊆ S') (x : G) (q : normalClosure S x) : normalClosure S' x
        => univ {G} {S} (normalClosure S') (\lam y<-S => superset S' (p y<-S)) x q
    }
}

{- | A decidable subgroup of a finite group. -}
\class FinSubGroup \extends DecSubGroup {
  \override S : FinGroup
} \where {
  \protected \lemma ext {G : FinGroup} {H K : FinSubGroup G} (p : \Pi (x : G) -> H x <-> K x) : H = K
    => exts \lam x => Paths.Meta.ext (p x)
}

\instance IFinGroup (S : FinSubGroup {}) : FinGroup
  | Group => IGroup S
  | FinSet => SigmaFin.DecSubSet-isFin S.S S

\instance SubGroupPoset {G : Group} : Poset (SubGroup G)
  | <= H K => H.contains ⊆ K.contains
  | <=-refl p => p
  | <=-transitive p q r => q (p r)
  | <=-antisymmetric p q => exts \lam g => ext (p,q)

\class SubAddGroup \extends SubAddMonoid {
  \override S : AddGroup
  | contains_negative {x : S} : contains x -> contains (negative x)

  \lemma contains_- {x y : S} : contains x -> contains y -> contains (x - y)
    => \lam cx cy => contains_+ cx (contains_negative cy)

  {- | A subgroup contains every integer multiple of each of its elements. -}
  \lemma contains_*i {x : S} (c : contains x) {n : Int} : contains (n AddGroup.*i x) \elim n
    | pos n => contains_*n c
    | neg n => contains_*n (contains_negative c)
} \where {
  \func max {A : AddGroup} : SubAddGroup \cowith
    | SubAddMonoid => SubAddMonoid.max {A}
    | contains_negative _ => ()

  \func maxHom {A : AddGroup} : AddGroupHom A (IAddGroup max) \cowith
    | AddMonoidHom => SubAddMonoid.maxHom
}

\instance IAddGroup (S : SubAddGroup {}) : AddGroup
  | AddMonoid => IAddMonoid S
  | negative x => (negative x.1, contains_negative x.2)
  | negative-left => ext negative-left
  | negative-right => ext negative-right
  \where
    \func embed : AddGroupHom (IAddGroup S) S.S \cowith
      | AddMonoidHom => IAddMonoid.embed

\instance IAbGroup {A : AbGroup} (S : SubAddGroup A) : AbGroup
  | AddGroup => IAddGroup S
  | +-comm => ext +-comm


\func KernelGroup (f : GroupHom) : NormalSubGroup f.Dom \cowith
  | SubMonoid => KernelMonoid f
  | contains_inverse p => f.func-inverse *> pmap inverse p *> inverse_ide
  | isNormal x {y} p => func-* *> pmap2 (*) (func-* *> pmap (_ *) p *> ide-right) f.func-inverse *> inverse-right

\lemma Kernel-trivial-char {f : GroupHom} : IsKernelTrivial f <-> IsInj f
  => (\lam kt {x} {y} p => (Group.makeInv (inverse y)).inv-cancel-right $
        kt (func-* *> pmap (_ *) f.func-inverse *> inv ((Group.makeInv (f y)).rotate-inv-right $ ide-left *> inv p)) *> inv inverse-right,
      \lam fi kx => fi $ kx *> inv f.func-ide)


\func KernelAddGroup (f : AddGroupHom) : SubAddGroup f.Dom \cowith
  | SubAddMonoid => KernelAddMonoid f
  | contains_negative p => f.func-negative *> pmap negative p *> AddGroup.negative_zro

\lemma AddKernel-trivial-char {f : AddGroupHom} : IsAddKernelTrivial f <-> IsInj f
  => Kernel-trivial-char {AddGroupHom.toGroupHom f}

{- | The preimage of a subgroup under a group homomorphism. -}
\func PreimageGroup (f : GroupHom) (H : SubGroup f.Cod) : SubGroup f.Dom \cowith
  | contains x => H (f x)
  | contains_ide => transportInv H f.func-ide H.contains_ide
  | contains_* p q => transportInv H f.func-* (H.contains_* p q)
  | contains_inverse p => transportInv H f.func-inverse (H.contains_inverse p)

\func ImageGroup (f : GroupHom) : SubGroup f.Cod \cowith
  | SubMonoid => ImageMonoid f
  | contains_inverse (inP (a, p)) => inP (inverse a, f.func-inverse *> pmap inverse p)

\func ImGroup (f : GroupHom) : Group
  => IGroup (ImageGroup f)

\func ImGroupLeftHom (f : GroupHom) : GroupHom f.Dom (ImGroup f) \cowith
  | MonoidHom => ImMonoidLeftHom f


\func ImageAddGroup (f : AddGroupHom) : SubAddGroup f.Cod \cowith
  | SubAddMonoid => ImageAddMonoid f
  | contains_negative (inP (a, p)) => inP (negative a, f.func-negative *> pmap negative p)

\func ImAddGroup (f : AddGroupHom) : AddGroup
  => IAddGroup (ImageAddGroup f)

\func ImAddGroupLeftHom (f : AddGroupHom) : AddGroupHom f.Dom (ImAddGroup f) \cowith
  | AddMonoidHom => ImAddMonoidLeftHom f