import Mathlib.GroupTheory.PresentedGroup
import Mathlib.Tactic.FinCases
import Mathlib.Tactic.Group
import Mathlib.Data.Fin.VecNotation
import Mathlib.Data.Fintype.Basic

/-! The one-factor obstruction in the Akbulut–Kirby family. -/
namespace AKOneT
open Function
abbrev Word (n : ℕ) := FreeGroup (Fin n)
abbrev gx : Word 2 := FreeGroup.of 0
abbrev gy : Word 2 := FreeGroup.of 1

def repL {α : Type*} : ℕ → List α → List α
  | 0, _ => []
  | n + 1, w => w ++ repL n w

theorem repL_succ_right {α : Type*} (n : ℕ) (w : List α) :
    repL (n + 1) w = repL n w ++ w := by
  induction n with
  | zero => simp [repL]
  | succ m ih => simp only [repL, List.append_assoc]; rw [← ih]; rfl

inductive C2C3Syl where
  | a  : C2C3Syl
  | c1 : C2C3Syl
  | c2 : C2C3Syl
  deriving DecidableEq, Repr

def sylOfFin : Fin 3 → C2C3Syl
  | 0 => .a | 1 => .c1 | 2 => .c2

def finOfSyl : C2C3Syl → Fin 3
  | .a => 0 | .c1 => 1 | .c2 => 2

theorem sylOfFin_finOfSyl (x : C2C3Syl) : sylOfFin (finOfSyl x) = x := by
  cases x <;> rfl

def isASyl : C2C3Syl → Bool
  | .a => true
  | _  => false

def isRedC2C3 : List C2C3Syl → Bool
  | [] => true
  | [_] => true
  | x :: y :: rest => (isASyl x != isASyl y) && isRedC2C3 (y :: rest)

abbrev RedC2C3 := { s : List C2C3Syl // isRedC2C3 s = true }

def actAList : List C2C3Syl → List C2C3Syl
  | .a :: rest => rest
  | rest => .a :: rest

def actCList : List C2C3Syl → List C2C3Syl
  | .c1 :: rest => .c2 :: rest
  | .c2 :: rest => rest
  | rest => .c1 :: rest

def actC2List (s : List C2C3Syl) : List C2C3Syl := actCList (actCList s)

def revInvSyl : C2C3Syl → C2C3Syl
  | .a  => .a
  | .c1 => .c2
  | .c2 => .c1

def revInvList (s : List C2C3Syl) : List C2C3Syl :=
  (s.map revInvSyl).reverse

theorem revInvSyl_involutive (x : C2C3Syl) : revInvSyl (revInvSyl x) = x := by
  cases x <;> rfl

theorem revInvList_involutive (s : List C2C3Syl) : revInvList (revInvList s) = s := by
  unfold revInvList
  rw [List.map_reverse, List.reverse_reverse, List.map_map]
  have hid : (revInvSyl ∘ revInvSyl) = id := funext revInvSyl_involutive
  rw [hid, List.map_id]

theorem revInvList_append (u v : List C2C3Syl) :
    revInvList (u ++ v) = revInvList v ++ revInvList u := by
  unfold revInvList
  rw [List.map_append, List.reverse_append]

theorem isASyl_revInvSyl (x : C2C3Syl) : isASyl (revInvSyl x) = isASyl x := by
  cases x <;> rfl

theorem isRedC2C3_append_singleton (s : List C2C3Syl) (y : C2C3Syl) :
    isRedC2C3 (s ++ [y]) =
      (isRedC2C3 s && match s.getLast? with | none => true | some z => isASyl z != isASyl y) := by
  induction s with
  | nil => rfl
  | cons x xs ih =>
      rcases xs with _ | ⟨x2, xs'⟩
      · simp [isRedC2C3]
      · change (isASyl x != isASyl x2 && isRedC2C3 ((x2 :: xs') ++ [y])) =
          ((isASyl x != isASyl x2 && isRedC2C3 (x2 :: xs')) &&
            match (x2 :: xs').getLast? with | none => true | some z => isASyl z != isASyl y)
        rw [ih, Bool.and_assoc]

theorem isRedC2C3_revInvList (s : List C2C3Syl) :
    isRedC2C3 (revInvList s) = isRedC2C3 s := by
  induction s with
  | nil => rfl
  | cons x xs ih =>
      unfold revInvList at ih ⊢
      rw [List.map_cons, List.reverse_cons, isRedC2C3_append_singleton, ih]
      rcases xs with _ | ⟨y, ys⟩
      · simp [isRedC2C3]
      · have hlast : ((y :: ys).map revInvSyl).reverse.getLast? = some (revInvSyl y) := by
          rw [List.map_cons, List.reverse_cons, List.getLast?_concat]
        rw [hlast]
        simp only [isRedC2C3, isASyl_revInvSyl]
        cases isASyl x <;> cases isASyl y <;> cases isRedC2C3 (y :: ys) <;> rfl

theorem isRedC2C3_actAList {s : List C2C3Syl} (hs : isRedC2C3 s = true) :
    isRedC2C3 (actAList s) = true := by
  rcases s with _ | ⟨x, _ | ⟨y, rest⟩⟩
  · rfl
  · cases x <;> rfl
  · cases x <;> cases y <;> simp [isRedC2C3, isASyl, actAList] at hs ⊢ <;> exact hs

theorem actAList_involutive {s : List C2C3Syl} (hs : isRedC2C3 s = true) :
    actAList (actAList s) = s := by
  rcases s with _ | ⟨x, _ | ⟨y, rest⟩⟩
  · rfl
  · cases x <;> rfl
  · cases x <;> cases y <;> simp [isRedC2C3, isASyl, actAList] at hs ⊢

theorem isRedC2C3_actCList {s : List C2C3Syl} (hs : isRedC2C3 s = true) :
    isRedC2C3 (actCList s) = true := by
  rcases s with _ | ⟨x, _ | ⟨y, rest⟩⟩
  · rfl
  · cases x <;> rfl
  · cases x <;> cases y <;> simp [isRedC2C3, isASyl, actCList] at hs ⊢ <;> exact hs

theorem actCList_order3 {s : List C2C3Syl} (hs : isRedC2C3 s = true) :
    actCList (actCList (actCList s)) = s := by
  rcases s with _ | ⟨x, _ | ⟨y, rest⟩⟩
  · rfl
  · cases x <;> rfl
  · cases x <;> cases y <;> simp [isRedC2C3, isASyl, actCList] at hs ⊢

def actA : Equiv.Perm RedC2C3 where
  toFun s := ⟨actAList s.1, isRedC2C3_actAList s.2⟩
  invFun s := ⟨actAList s.1, isRedC2C3_actAList s.2⟩
  left_inv s := Subtype.ext (actAList_involutive s.2)
  right_inv s := Subtype.ext (actAList_involutive s.2)

def actC : Equiv.Perm RedC2C3 where
  toFun s := ⟨actCList s.1, isRedC2C3_actCList s.2⟩
  invFun s := ⟨actC2List s.1, isRedC2C3_actCList (isRedC2C3_actCList s.2)⟩
  left_inv s := Subtype.ext (actCList_order3 s.2)
  right_inv s := Subtype.ext (actCList_order3 s.2)

def permX : Equiv.Perm RedC2C3 := actC ^ 2 * actA
def permY : Equiv.Perm RedC2C3 := actA * actC ^ 2

theorem actA_sq : actA * actA = 1 := by
  apply Equiv.ext; intro s; exact Subtype.ext (actAList_involutive s.2)

theorem actC_cube : actC ^ 3 = 1 := by
  apply Equiv.ext; intro s
  change (actC (actC (actC s))) = s
  exact Subtype.ext (actCList_order3 s.2)

theorem permX_permY_braid : permX * permY * permX = permY * permX * permY := by
  apply Equiv.ext; intro s
  rcases s with ⟨L, hL⟩
  apply Subtype.ext
  change actCList (actCList (actAList (actAList (actCList (actCList (actCList (actCList (actAList L)))))))) =
    actAList (actCList (actCList (actCList (actCList (actAList (actAList (actCList (actCList L))))))))
  have h1 : isRedC2C3 (actAList L) = true := isRedC2C3_actAList hL
  have h2 : actCList (actCList (actCList (actCList (actAList L)))) = actCList (actAList L) := by
    rw [actCList_order3 h1]
  rw [h2, actAList_involutive (isRedC2C3_actCList h1), actCList_order3 h1]
  have h3 : isRedC2C3 (actCList (actCList L)) = true := isRedC2C3_actCList (isRedC2C3_actCList hL)
  rw [actAList_involutive h3, actCList_order3 (isRedC2C3_actCList hL), actCList_order3 hL]

def rhoC2C3 : Word 2 →* Equiv.Perm RedC2C3 :=
  FreeGroup.lift ![permX, permY]

@[simp] theorem rhoC2C3_gx : rhoC2C3 gx = permX := by
  simp [rhoC2C3, gx, FreeGroup.lift_apply_of]

@[simp] theorem rhoC2C3_gy : rhoC2C3 gy = permY := by
  simp [rhoC2C3, gy, FreeGroup.lift_apply_of]

def relAK : Word 2 := gy⁻¹ * gx⁻¹ * gy⁻¹ * gx * gy * gx

theorem rhoC2C3_relAK : rhoC2C3 relAK = 1 := by
  unfold relAK
  simp only [map_mul, map_inv, rhoC2C3_gx, rhoC2C3_gy]
  calc permY⁻¹ * permX⁻¹ * permY⁻¹ * permX * permY * permX
      = (permY * permX * permY)⁻¹ * (permX * permY * permX) := by group
    _ = (permX * permY * permX)⁻¹ * (permX * permY * permX) := by rw [← permX_permY_braid]
    _ = 1 := inv_mul_cancel _

def actARightList (s : List C2C3Syl) : List C2C3Syl :=
  revInvList (actAList (revInvList s))

def actC2RightList (s : List C2C3Syl) : List C2C3Syl :=
  revInvList (actCList (revInvList s))

theorem actARightList_snoc (pre : List C2C3Syl) (y : C2C3Syl) :
    actARightList (pre ++ [y]) =
      match y with
      | .a => pre
      | _  => pre ++ [y, .a] := by
  unfold actARightList
  rw [revInvList_append]
  cases y
  · change revInvList (actAList (.a :: revInvList pre)) = pre
    simp only [actAList, revInvList_involutive]
  · change revInvList ([.a, .c2] ++ revInvList pre) = pre ++ [.c1, .a]
    rw [revInvList_append, revInvList_involutive]; rfl
  · change revInvList ([.a, .c1] ++ revInvList pre) = pre ++ [.c2, .a]
    rw [revInvList_append, revInvList_involutive]; rfl

theorem actC2RightList_snoc (pre : List C2C3Syl) (y : C2C3Syl) :
    actC2RightList (pre ++ [y]) =
      match y with
      | .c1 => pre
      | .c2 => pre ++ [.c1]
      | .a  => pre ++ [.a, .c2] := by
  unfold actC2RightList
  rw [revInvList_append]
  cases y
  · change revInvList ([.c1, .a] ++ revInvList pre) = pre ++ [.a, .c2]
    rw [revInvList_append, revInvList_involutive]; rfl
  · change revInvList (actCList (.c2 :: revInvList pre)) = pre
    simp only [actCList, revInvList_involutive]
  · change revInvList ([.c2] ++ revInvList pre) = pre ++ [.c1]
    rw [revInvList_append, revInvList_involutive]; rfl

theorem actARightList_cons_cons (x u : C2C3Syl) (tl : List C2C3Syl) :
    actARightList (x :: u :: tl) = x :: actARightList (u :: tl) := by
  rcases List.eq_nil_or_concat tl with rfl | ⟨m, y, hcat⟩
  · cases x <;> cases u <;> rfl
  · rw [List.concat_eq_append] at hcat; subst hcat
    have h1 : x :: u :: (m ++ [y]) = (x :: u :: m) ++ [y] := rfl
    have h2 : u :: (m ++ [y]) = (u :: m) ++ [y] := rfl
    rw [h1, h2, actARightList_snoc, actARightList_snoc]
    cases y <;> rfl

theorem actC2RightList_cons_cons (x u : C2C3Syl) (tl : List C2C3Syl) :
    actC2RightList (x :: u :: tl) = x :: actC2RightList (u :: tl) := by
  rcases List.eq_nil_or_concat tl with rfl | ⟨m, y, hcat⟩
  · cases x <;> cases u <;> rfl
  · rw [List.concat_eq_append] at hcat; subst hcat
    have h1 : x :: u :: (m ++ [y]) = (x :: u :: m) ++ [y] := rfl
    have h2 : u :: (m ++ [y]) = (u :: m) ++ [y] := rfl
    rw [h1, h2, actC2RightList_snoc, actC2RightList_snoc]
    cases y <;> rfl

def actARight : Equiv.Perm RedC2C3 where
  toFun s := ⟨actARightList s.1, by
    unfold actARightList; rw [isRedC2C3_revInvList]
    exact isRedC2C3_actAList (by rw [isRedC2C3_revInvList]; exact s.2)⟩
  invFun s := ⟨actARightList s.1, by
    unfold actARightList; rw [isRedC2C3_revInvList]
    exact isRedC2C3_actAList (by rw [isRedC2C3_revInvList]; exact s.2)⟩
  left_inv s := Subtype.ext (by
    dsimp only; unfold actARightList
    rw [revInvList_involutive, actAList_involutive (by rw [isRedC2C3_revInvList]; exact s.2),
      revInvList_involutive])
  right_inv s := Subtype.ext (by
    dsimp only; unfold actARightList
    rw [revInvList_involutive, actAList_involutive (by rw [isRedC2C3_revInvList]; exact s.2),
      revInvList_involutive])

def actC2Right : Equiv.Perm RedC2C3 where
  toFun s := ⟨actC2RightList s.1, by
    unfold actC2RightList; rw [isRedC2C3_revInvList]
    exact isRedC2C3_actCList (by rw [isRedC2C3_revInvList]; exact s.2)⟩
  invFun s := ⟨revInvList (actC2List (revInvList s.1)), by
    rw [isRedC2C3_revInvList]
    exact isRedC2C3_actCList (isRedC2C3_actCList (by rw [isRedC2C3_revInvList]; exact s.2))⟩
  left_inv s := Subtype.ext (by
    dsimp only; unfold actC2RightList actC2List
    rw [revInvList_involutive, actCList_order3 (by rw [isRedC2C3_revInvList]; exact s.2),
      revInvList_involutive])
  right_inv s := Subtype.ext (by
    dsimp only; unfold actC2RightList actC2List
    rw [revInvList_involutive, actCList_order3 (by rw [isRedC2C3_revInvList]; exact s.2),
      revInvList_involutive])

private def checkCommShort (s : List C2C3Syl) : Bool :=
  !(isRedC2C3 s) ||
  (decide (actAList (actARightList s) = actARightList (actAList s)) &&
   decide (actAList (actC2RightList s) = actC2RightList (actAList s)) &&
   decide (actCList (actARightList s) = actARightList (actCList s)) &&
   decide (actCList (actC2RightList s) = actC2RightList (actCList s)))

private theorem comm_short_check :
    checkCommShort [] = true ∧
    (∀ i : Fin 3, checkCommShort [sylOfFin i] = true) ∧
    (∀ i j : Fin 3, checkCommShort [sylOfFin i, sylOfFin j] = true) :=
  of_decide_eq_true rfl

theorem left_right_comm_lists (s : List C2C3Syl) (hs : isRedC2C3 s = true) :
    actAList (actARightList s) = actARightList (actAList s) ∧
    actAList (actC2RightList s) = actC2RightList (actAList s) ∧
    actCList (actARightList s) = actARightList (actCList s) ∧
    actCList (actC2RightList s) = actC2RightList (actCList s) := by
  rcases s with _ | ⟨x1, _ | ⟨x2, _ | ⟨x3, rest⟩⟩⟩
  · decide
  · have h := comm_short_check.2.1 (finOfSyl x1)
    rw [sylOfFin_finOfSyl] at h
    unfold checkCommShort at h
    simp only [hs, Bool.not_true, Bool.false_or, Bool.and_eq_true, decide_eq_true_eq] at h
    exact ⟨h.1.1.1, h.1.1.2, h.1.2, h.2⟩
  · have h := comm_short_check.2.2 (finOfSyl x1) (finOfSyl x2)
    rw [sylOfFin_finOfSyl, sylOfFin_finOfSyl] at h
    unfold checkCommShort at h
    simp only [hs, Bool.not_true, Bool.false_or, Bool.and_eq_true, decide_eq_true_eq] at h
    exact ⟨h.1.1.1, h.1.1.2, h.1.2, h.2⟩
  · cases x1 <;> simp [actARightList_cons_cons, actC2RightList_cons_cons, actAList, actCList]

theorem act_commutes_for_closure {u : Equiv.Perm RedC2C3}
    (hu : u ∈ Subgroup.closure ({actA, actC} : Set (Equiv.Perm RedC2C3))) :
    ∀ s : RedC2C3, u (actARight s) = actARight (u s) ∧ u (actC2Right s) = actC2Right (u s) := by
  refine Subgroup.closure_induction ?_ ?_ ?_ ?_ hu
  · intro g hg s
    rcases Set.mem_insert_iff.mp hg with rfl | hg2
    · exact ⟨Subtype.ext (left_right_comm_lists s.1 s.2).1,
             Subtype.ext (left_right_comm_lists s.1 s.2).2.1⟩
    · have hgc : g = actC := Set.mem_singleton_iff.mp hg2
      subst hgc
      exact ⟨Subtype.ext (left_right_comm_lists s.1 s.2).2.2.1,
             Subtype.ext (left_right_comm_lists s.1 s.2).2.2.2⟩
  · intro _; exact ⟨rfl, rfl⟩
  · intro g1 g2 _ _ ih1 ih2 s
    change (g1 (g2 (actARight s)) = actARight (g1 (g2 s))) ∧
           (g1 (g2 (actC2Right s)) = actC2Right (g1 (g2 s)))
    rw [(ih2 s).1, (ih1 (g2 s)).1, (ih2 s).2, (ih1 (g2 s)).2]
    exact ⟨rfl, rfl⟩
  · intro g _ ih s
    have hgg : ∀ x, g (g⁻¹ x) = x := fun x => by
      change (g * g⁻¹) x = x; rw [mul_inv_cancel]; rfl
    constructor
    · apply g.injective; rw [hgg, (ih (g⁻¹ s)).1, hgg]
    · apply g.injective; rw [hgg, (ih (g⁻¹ s)).2, hgg]

theorem rhoC2C3_mem_closure (w : Word 2) :
    rhoC2C3 w ∈ Subgroup.closure ({actA, actC} : Set (Equiv.Perm RedC2C3)) := by
  let H := Subgroup.closure ({actA, actC} : Set (Equiv.Perm RedC2C3))
  have ha : actA ∈ H := Subgroup.subset_closure (Set.mem_insert _ _)
  have hc : actC ∈ H := Subgroup.subset_closure (Set.mem_insert_of_mem _ (Set.mem_singleton _))
  have hx : permX ∈ H := H.mul_mem (H.pow_mem hc 2) ha
  have hy : permY ∈ H := H.mul_mem ha (H.pow_mem hc 2)
  refine @Quot.ind _ _ (fun z => rhoC2C3 z ∈ H) (fun L => ?_) w
  dsimp only
  change rhoC2C3 (FreeGroup.mk L) ∈ H
  induction L with
  | nil => exact H.one_mem
  | cons g gs ih =>
      have hcons : FreeGroup.mk (g :: gs) = FreeGroup.mk [g] * FreeGroup.mk gs := by
        rw [FreeGroup.mul_mk]; rfl
      rw [hcons, map_mul]
      refine H.mul_mem ?_ ih
      obtain ⟨i, b⟩ := g
      fin_cases i <;> cases b
      · change rhoC2C3 gx⁻¹ ∈ H
        rw [map_inv, rhoC2C3_gx]; exact H.inv_mem hx
      · change rhoC2C3 gx ∈ H
        rw [rhoC2C3_gx]; exact hx
      · change rhoC2C3 gy⁻¹ ∈ H
        rw [map_inv, rhoC2C3_gy]; exact H.inv_mem hy
      · change rhoC2C3 gy ∈ H
        rw [rhoC2C3_gy]; exact hy

def emptyRed : RedC2C3 := ⟨[], rfl⟩
def evalWord (u : Equiv.Perm RedC2C3) : List C2C3Syl := (u emptyRed).1

theorem evalWord_conj_actA {u : Equiv.Perm RedC2C3}
    (hu : u ∈ Subgroup.closure ({actA, actC} : Set (Equiv.Perm RedC2C3))) :
    evalWord (actA * u * actA⁻¹) = actAList (actARightList (evalWord u)) := by
  unfold evalWord
  have hinv : actA⁻¹ emptyRed = actARight emptyRed := rfl
  change (actA (u (actA⁻¹ emptyRed))).1 = _
  rw [hinv, (act_commutes_for_closure hu emptyRed).1]
  rfl

theorem evalWord_conj_actC {u : Equiv.Perm RedC2C3}
    (hu : u ∈ Subgroup.closure ({actA, actC} : Set (Equiv.Perm RedC2C3))) :
    evalWord (actC * u * actC⁻¹) = actCList (actC2RightList (evalWord u)) := by
  unfold evalWord
  have hinv : actC⁻¹ emptyRed = actC2Right emptyRed := rfl
  change (actC (u (actC⁻¹ emptyRed))).1 = _
  rw [hinv, (act_commutes_for_closure hu emptyRed).2]
  rfl

def cResidues : List C2C3Syl → List Bool
  | [] => []
  | .a :: xs => cResidues xs
  | .c1 :: xs => false :: cResidues xs
  | .c2 :: xs => true :: cResidues xs

theorem cResidues_append (u v : List C2C3Syl) :
    cResidues (u ++ v) = cResidues u ++ cResidues v := by
  induction u with
  | nil => rfl
  | cons x xs ih => cases x <;> simp [cResidues, ih]

def cycStepC2C3 (s : List C2C3Syl) : Option (List C2C3Syl) :=
  match s with
  | [] => none
  | [_] => none
  | x :: rest =>
      match rest.reverse with
      | [] => none
      | y :: rinit =>
          let mid := rinit.reverse
          match x, y with
          | .a,  .a  => some mid
          | .c1, .c2 => some mid
          | .c2, .c1 => some mid
          | .c1, .c1 => some (.c2 :: mid)
          | .c2, .c2 => some (.c1 :: mid)
          | _,   _   => none

def cycRedAux : ℕ → List C2C3Syl → List Bool
  | 0, s => cResidues s
  | fuel + 1, s =>
      match cycStepC2C3 s with
      | none => cResidues s
      | some s' => cycRedAux fuel s'

def cycRedC2C3 (s : List C2C3Syl) : List Bool :=
  cycRedAux s.length s

theorem cycStepC2C3_length_lt {s s' : List C2C3Syl} (h : cycStepC2C3 s = some s') :
    s'.length < s.length := by
  rcases s with _ | ⟨x, _ | ⟨x2, xs⟩⟩
  · cases h
  · cases h
  · dsimp only [cycStepC2C3] at h
    rcases hrev : (x2 :: xs).reverse with _ | ⟨y, rinit⟩
    · rw [hrev] at h; cases h
    · rw [hrev] at h
      have hlen : (x2 :: xs).length = rinit.length + 1 := by
        have := congrArg List.length hrev
        simpa using this
      cases x <;> cases y <;> simp at h
      all_goals
        subst h
        simp [List.length_reverse, hlen] <;> omega

theorem cycRedAux_eq_cycRedC2C3 :
    ∀ (fuel : ℕ) (s : List C2C3Syl), s.length ≤ fuel → cycRedAux fuel s = cycRedC2C3 s
  | 0, s, hle => by
      have hs : s = [] := List.eq_nil_of_length_eq_zero (by omega)
      subst hs; rfl
  | fuel + 1, s, hle => by
      unfold cycRedC2C3
      rcases hlen : s.length with _ | m
      · have hs : s = [] := List.eq_nil_of_length_eq_zero hlen
        subst hs; rfl
      · simp only [cycRedAux]
        cases hst : cycStepC2C3 s with
        | none => rfl
        | some s' =>
            have hlt := cycStepC2C3_length_lt hst
            have h1 := cycRedAux_eq_cycRedC2C3 fuel s' (by omega)
            have h2 := cycRedAux_eq_cycRedC2C3 m s' (by omega)
            exact h1.trans h2.symm

theorem cycRedC2C3_step_some {s s' : List C2C3Syl} (h : cycStepC2C3 s = some s') :
    cycRedC2C3 s = cycRedC2C3 s' := by
  have hlt := cycStepC2C3_length_lt h
  obtain ⟨m, hm⟩ : ∃ m, s.length = m + 1 := ⟨s.length - 1, by omega⟩
  unfold cycRedC2C3
  rw [hm]
  simp only [cycRedAux, h]
  exact cycRedAux_eq_cycRedC2C3 m s' (by omega)

theorem cycRedC2C3_step_none {s : List C2C3Syl} (h : cycStepC2C3 s = none) :
    cycRedC2C3 s = cResidues s := by
  unfold cycRedC2C3
  cases s.length <;> simp [cycRedAux, h]

theorem cycStepC2C3_snoc (x y : C2C3Syl) (mid : List C2C3Syl) :
    cycStepC2C3 (x :: (mid ++ [y])) =
      match x, y with
      | .a,  .a  => some mid
      | .c1, .c2 => some mid
      | .c2, .c1 => some mid
      | .c1, .c1 => some (.c2 :: mid)
      | .c2, .c2 => some (.c1 :: mid)
      | _,   _   => none := by
  unfold cycStepC2C3
  rcases mid with _ | ⟨m0, ms⟩ <;> simp

-- Explicit `s` in `cycRed_snoc_*` so `rw` always rewrites the exact intended side!
private theorem cycRed_snoc_aa (s m : List C2C3Syl)
    (heq : s = .a :: (m ++ [.a])) : cycRedC2C3 s = cycRedC2C3 m := by
  rw [heq]; exact cycRedC2C3_step_some (by rw [cycStepC2C3_snoc])

private theorem cycRed_snoc_c1c2 (s m : List C2C3Syl)
    (heq : s = .c1 :: (m ++ [.c2])) : cycRedC2C3 s = cycRedC2C3 m := by
  rw [heq]; exact cycRedC2C3_step_some (by rw [cycStepC2C3_snoc])

private theorem cycRed_snoc_c2c1 (s m : List C2C3Syl)
    (heq : s = .c2 :: (m ++ [.c1])) : cycRedC2C3 s = cycRedC2C3 m := by
  rw [heq]; exact cycRedC2C3_step_some (by rw [cycStepC2C3_snoc])

private theorem cycRed_snoc_c1c1 (s m : List C2C3Syl)
    (heq : s = .c1 :: (m ++ [.c1])) : cycRedC2C3 s = cycRedC2C3 (.c2 :: m) := by
  rw [heq]; exact cycRedC2C3_step_some (by rw [cycStepC2C3_snoc])

private theorem cycRed_snoc_c2c2 (s m : List C2C3Syl)
    (heq : s = .c2 :: (m ++ [.c2])) : cycRedC2C3 s = cycRedC2C3 (.c1 :: m) := by
  rw [heq]; exact cycRedC2C3_step_some (by rw [cycStepC2C3_snoc])

private theorem cycRed_snoc_ac1 (s m : List C2C3Syl)
    (heq : s = .a :: (m ++ [.c1])) : cycRedC2C3 s = cResidues s := by
  rw [heq]; exact cycRedC2C3_step_none (by rw [cycStepC2C3_snoc])

private theorem cycRed_snoc_ac2 (s m : List C2C3Syl)
    (heq : s = .a :: (m ++ [.c2])) : cycRedC2C3 s = cResidues s := by
  rw [heq]; exact cycRedC2C3_step_none (by rw [cycStepC2C3_snoc])

private theorem cycRed_snoc_c1a (s m : List C2C3Syl)
    (heq : s = .c1 :: (m ++ [.a])) : cycRedC2C3 s = cResidues s := by
  rw [heq]; exact cycRedC2C3_step_none (by rw [cycStepC2C3_snoc])

private theorem cycRed_snoc_c2a (s m : List C2C3Syl)
    (heq : s = .c2 :: (m ++ [.a])) : cycRedC2C3 s = cResidues s := by
  rw [heq]; exact cycRedC2C3_step_none (by rw [cycStepC2C3_snoc])

/-- Polymorphic cyclic rotation step and equivalence relation on `List α`. -/
def RotStep {α : Type*} (u v : List α) : Prop :=
  ∃ p s : List α, u = p ++ s ∧ v = s ++ p

def IsRotEqv {α : Type*} : List α → List α → Prop :=
  Relation.EqvGen RotStep

def isRotBool (u v : List Bool) : Bool :=
  (List.range (v.length + 1)).any (fun i => decide (v.drop i ++ v.take i = u))

theorem isRotEqv_of_isRotBool {u v : List Bool} (h : isRotBool u v = true) :
    IsRotEqv u v := by
  unfold isRotBool at h
  obtain ⟨i, _, hi⟩ := List.any_eq_true.mp h
  simp only [decide_eq_true_eq] at hi
  exact Relation.EqvGen.rel _ _ ⟨v.drop i, v.take i, hi.symm, (List.take_append_drop i v).symm⟩

private def checkConjShort (s : List C2C3Syl) : Bool :=
  !(isRedC2C3 s) ||
  (decide (cycRedC2C3 (actAList (actARightList s)) = cycRedC2C3 s) &&
   isRotBool (cycRedC2C3 (actCList (actC2RightList s))) (cycRedC2C3 s))

private theorem conj_short_check :
    checkConjShort [] = true ∧
    (∀ i : Fin 3, checkConjShort [sylOfFin i] = true) ∧
    (∀ i j : Fin 3, checkConjShort [sylOfFin i, sylOfFin j] = true) ∧
    (∀ i j k : Fin 3, checkConjShort [sylOfFin i, sylOfFin j, sylOfFin k] = true) ∧
    (∀ i j k l : Fin 3, checkConjShort [sylOfFin i, sylOfFin j, sylOfFin k, sylOfFin l] = true) :=
  of_decide_eq_true rfl

private theorem unpack_conj_short {s : List C2C3Syl} (hs : isRedC2C3 s = true)
    (hc : checkConjShort s = true) :
    cycRedC2C3 (actAList (actARightList s)) = cycRedC2C3 s ∧
    IsRotEqv (cycRedC2C3 (actCList (actC2RightList s))) (cycRedC2C3 s) := by
  unfold checkConjShort at hc
  simp only [hs, Bool.not_true, Bool.false_or, Bool.and_eq_true, decide_eq_true_eq] at hc
  exact ⟨hc.1, isRotEqv_of_isRotBool hc.2⟩

theorem split_last_two {α : Type*} (a b : α) (rest : List α) :
    ∃ (mid : List α) (y2 y1 : α), a :: b :: rest = mid ++ [y2, y1] := by
  induction rest generalizing a b with
  | nil => exact ⟨[], a, b, rfl⟩
  | cons c cs ih =>
      obtain ⟨mid, y2, y1, heq⟩ := ih b c
      exact ⟨a :: mid, y2, y1, by simp [heq]⟩

/-- Simultaneous proof for `conjA` (`=`) and `conjC` (`IsRotEqv`) in 9 structural cases. -/
theorem cycRedC2C3_conjA_and_conjC (s : List C2C3Syl) (hs : isRedC2C3 s = true) :
    cycRedC2C3 (actAList (actARightList s)) = cycRedC2C3 s ∧
    IsRotEqv (cycRedC2C3 (actCList (actC2RightList s))) (cycRedC2C3 s) := by
  rcases s with _ | ⟨x1, _ | ⟨x2, _ | ⟨x3, _ | ⟨x4, rest⟩⟩⟩⟩
  · exact unpack_conj_short hs conj_short_check.1
  · have h := conj_short_check.2.1 (finOfSyl x1)
    rw [sylOfFin_finOfSyl] at h
    exact unpack_conj_short hs h
  · have h := conj_short_check.2.2.1 (finOfSyl x1) (finOfSyl x2)
    rw [sylOfFin_finOfSyl, sylOfFin_finOfSyl] at h
    exact unpack_conj_short hs h
  · have h := conj_short_check.2.2.2.1 (finOfSyl x1) (finOfSyl x2) (finOfSyl x3)
    rw [sylOfFin_finOfSyl, sylOfFin_finOfSyl, sylOfFin_finOfSyl] at h
    exact unpack_conj_short hs h
  · rcases rest with _ | ⟨x5, tail5⟩
    · have h := conj_short_check.2.2.2.2 (finOfSyl x1) (finOfSyl x2) (finOfSyl x3) (finOfSyl x4)
      rw [sylOfFin_finOfSyl, sylOfFin_finOfSyl, sylOfFin_finOfSyl, sylOfFin_finOfSyl] at h
      exact unpack_conj_short hs h
    · obtain ⟨mid, y2, y1, hsplit⟩ := split_last_two x3 x4 (x5 :: tail5)
      have hfull : x1 :: x2 :: x3 :: x4 :: x5 :: tail5 = x1 :: x2 :: (mid ++ [y2, y1]) := by
        rw [hsplit]
      rw [hfull] at hs ⊢
      have h12 : isASyl x1 ≠ isASyl x2 := by simp [isRedC2C3] at hs; exact hs.1
      have hy_adj : isASyl y2 ≠ isASyl y1 := by
        have hcat : x1 :: x2 :: (mid ++ [y2, y1]) = (x1 :: x2 :: mid ++ [y2]) ++ [y1] := by simp
        have hlast : (x1 :: x2 :: mid ++ [y2]).getLast? = some y2 := by
          rw [List.getLast?_concat]
        have hs' := hs
        rw [hcat, isRedC2C3_append_singleton, hlast] at hs'
        simp at hs'
        exact hs'.2
      have hsnoc_form : ∀ u v z, u :: v :: (mid ++ [y2, z]) = (u :: v :: mid ++ [y2]) ++ [z] := by
        intro _ _ _; simp
      cases x1
      · -- x1 = .a => x2 ≠ .a
        have hx2_not_a : x2 ≠ .a := by intro he; subst he; exact h12 rfl
        cases y1
        · -- Case 1/9: (.a .. .a)
          refine ⟨?_, ?_⟩
          · rw [hsnoc_form, actARightList_snoc]
            have hL : actAList (.a :: x2 :: mid ++ [y2]) = x2 :: mid ++ [y2] := rfl
            have hR := cycRed_snoc_aa ((.a :: x2 :: mid ++ [y2]) ++ [.a]) (x2 :: mid ++ [y2])
              (by simp [List.append_assoc])
            rw [hL, hR]
          · rw [hsnoc_form, actC2RightList_snoc]
            have hL := cycRed_snoc_c1c2
              (actCList ((.a :: x2 :: mid ++ [y2]) ++ [.a, .c2]))
              (.a :: x2 :: mid ++ [y2, .a])
              (by simp [actCList, List.append_assoc])
            rw [hL]
            have heq0 : (.a :: x2 :: mid ++ [y2, .a]) = (.a :: x2 :: mid ++ [y2]) ++ [.a] := by
              simp [List.append_assoc]
            rw [heq0]
            exact Relation.EqvGen.refl _
        · -- Case 2/9: (.a .. .c1) => y2 = .a
          have hy2 : y2 = .a := by
            cases y2
            · rfl
            · exact absurd rfl hy_adj
            · exact absurd rfl hy_adj
          subst hy2
          refine ⟨?_, ?_⟩
          · rw [hsnoc_form, actARightList_snoc]
            have haL : actAList ((.a :: x2 :: mid ++ [.a]) ++ [.c1, .a]) =
                x2 :: ((mid ++ [.a, .c1]) ++ [.a]) := by simp [actAList, List.append_assoc]
            have hnone1 : cycRedC2C3 (x2 :: ((mid ++ [.a, .c1]) ++ [.a])) =
                cResidues (x2 :: ((mid ++ [.a, .c1]) ++ [.a])) := by
              cases x2
              · exact absurd rfl hx2_not_a
              · exact cycRed_snoc_c1a _ _ rfl
              · exact cycRed_snoc_c2a _ _ rfl
            have hR := cycRed_snoc_ac1 ((.a :: x2 :: mid ++ [.a]) ++ [.c1]) (x2 :: mid ++ [.a])
              (by simp [List.append_assoc])
            rw [haL, hnone1, hR]
            cases x2 <;> simp [cResidues, cResidues_append, List.append_assoc]
          · rw [hsnoc_form, actC2RightList_snoc]
            have hL := cycRed_snoc_c1a (actCList (.a :: x2 :: mid ++ [.a])) (.a :: x2 :: mid)
              (by simp [actCList])
            have hR := cycRed_snoc_ac1 ((.a :: x2 :: mid ++ [.a]) ++ [.c1]) (x2 :: mid ++ [.a])
              (by simp [List.append_assoc])
            rw [hL, hR]
            apply Relation.EqvGen.rel
            refine ⟨[false], cResidues (x2 :: mid), ?_, ?_⟩
            · cases x2 <;> simp [actCList, cResidues, cResidues_append]
            · cases x2 <;> simp [cResidues, cResidues_append, List.append_assoc]
        · -- Case 3/9: (.a .. .c2) => y2 = .a
          have hy2 : y2 = .a := by
            cases y2
            · rfl
            · exact absurd rfl hy_adj
            · exact absurd rfl hy_adj
          subst hy2
          refine ⟨?_, ?_⟩
          · rw [hsnoc_form, actARightList_snoc]
            have haL : actAList ((.a :: x2 :: mid ++ [.a]) ++ [.c2, .a]) =
                x2 :: ((mid ++ [.a, .c2]) ++ [.a]) := by simp [actAList, List.append_assoc]
            have hnone1 : cycRedC2C3 (x2 :: ((mid ++ [.a, .c2]) ++ [.a])) =
                cResidues (x2 :: ((mid ++ [.a, .c2]) ++ [.a])) := by
              cases x2
              · exact absurd rfl hx2_not_a
              · exact cycRed_snoc_c1a _ _ rfl
              · exact cycRed_snoc_c2a _ _ rfl
            have hR := cycRed_snoc_ac2 ((.a :: x2 :: mid ++ [.a]) ++ [.c2]) (x2 :: mid ++ [.a])
              (by simp [List.append_assoc])
            rw [haL, hnone1, hR]
            cases x2 <;> simp [cResidues, cResidues_append, List.append_assoc]
          · rw [hsnoc_form, actC2RightList_snoc]
            have hL1 := cycRed_snoc_c1c1 (actCList ((.a :: x2 :: mid ++ [.a]) ++ [.c1]))
              (.a :: x2 :: mid ++ [.a]) (by simp [actCList, List.append_assoc])
            have hL2 := cycRed_snoc_c2a (.c2 :: (.a :: x2 :: mid ++ [.a])) (.a :: x2 :: mid)
              (by simp)
            have hR := cycRed_snoc_ac2 ((.a :: x2 :: mid ++ [.a]) ++ [.c2]) (x2 :: mid ++ [.a])
              (by simp [List.append_assoc])
            rw [hL1, hL2, hR]
            apply Relation.EqvGen.rel
            refine ⟨[true], cResidues (x2 :: mid), ?_, ?_⟩
            · cases x2 <;> simp [cResidues, cResidues_append]
            · cases x2 <;> simp [cResidues, cResidues_append, List.append_assoc]
      · -- x1 = .c1 => x2 = .a
        have hx2 : x2 = .a := by
          cases x2
          · rfl
          · exact absurd rfl h12
          · exact absurd rfl h12
        subst hx2
        cases y1
        · -- Case 4/9: (.c1 .. .a) => y2 ≠ .a
          have hy2_not_a : y2 ≠ .a := by intro he; subst he; exact hy_adj rfl
          refine ⟨?_, ?_⟩
          · rw [hsnoc_form, actARightList_snoc]
            have hnone1 : cycRedC2C3 (actAList (.c1 :: .a :: mid ++ [y2])) =
                cResidues (actAList (.c1 :: .a :: mid ++ [y2])) := by
              cases y2
              · exact absurd rfl hy2_not_a
              · exact cycRed_snoc_ac1 _ (.c1 :: .a :: mid) (by simp [actAList])
              · exact cycRed_snoc_ac2 _ (.c1 :: .a :: mid) (by simp [actAList])
            have hR := cycRed_snoc_c1a ((.c1 :: .a :: mid ++ [y2]) ++ [.a]) (.a :: mid ++ [y2])
              (by simp [List.append_assoc])
            rw [hnone1, hR]
            cases y2 <;> simp [actAList, cResidues, cResidues_append, List.append_assoc]
          · rw [hsnoc_form, actC2RightList_snoc]
            have hL := cycRed_snoc_c2c2 (actCList ((.c1 :: .a :: mid ++ [y2]) ++ [.a, .c2]))
              (.a :: mid ++ [y2, .a]) (by simp [actCList, List.append_assoc])
            rw [hL]
            have heq0 : .c1 :: (.a :: mid ++ [y2, .a]) = (.c1 :: .a :: mid ++ [y2]) ++ [.a] := by
              simp [List.append_assoc]
            rw [heq0]
            exact Relation.EqvGen.refl _
        · -- Case 5/9: (.c1 .. .c1) => y2 = .a
          have hy2 : y2 = .a := by
            cases y2
            · rfl
            · exact absurd rfl hy_adj
            · exact absurd rfl hy_adj
          subst hy2
          refine ⟨?_, ?_⟩
          · rw [hsnoc_form, actARightList_snoc]
            have hL := cycRed_snoc_aa (actAList ((.c1 :: .a :: mid ++ [.a]) ++ [.c1, .a]))
              (.c1 :: .a :: mid ++ [.a, .c1]) (by simp [actAList, List.append_assoc])
            rw [hL]
            simp [List.append_assoc]
          · rw [hsnoc_form, actC2RightList_snoc]
            have hcL : actCList (.c1 :: .a :: mid ++ [.a]) = .c2 :: (.a :: mid ++ [.a]) := by
              simp [actCList]
            have hR := cycRed_snoc_c1c1 ((.c1 :: .a :: mid ++ [.a]) ++ [.c1]) (.a :: mid ++ [.a])
              (by simp [List.append_assoc])
            rw [hcL, hR]
            exact Relation.EqvGen.refl _
        · -- Case 6/9: (.c1 .. .c2) => y2 = .a
          have hy2 : y2 = .a := by
            cases y2
            · rfl
            · exact absurd rfl hy_adj
            · exact absurd rfl hy_adj
          subst hy2
          refine ⟨?_, ?_⟩
          · rw [hsnoc_form, actARightList_snoc]
            have hL := cycRed_snoc_aa (actAList ((.c1 :: .a :: mid ++ [.a]) ++ [.c2, .a]))
              (.c1 :: .a :: mid ++ [.a, .c2]) (by simp [actAList, List.append_assoc])
            rw [hL]
            simp [List.append_assoc]
          · rw [hsnoc_form, actC2RightList_snoc]
            have hL := cycRed_snoc_c2c1 (actCList ((.c1 :: .a :: mid ++ [.a]) ++ [.c1]))
              (.a :: mid ++ [.a]) (by simp [actCList, List.append_assoc])
            have hR := cycRed_snoc_c1c2 ((.c1 :: .a :: mid ++ [.a]) ++ [.c2])
              (.a :: mid ++ [.a]) (by simp [List.append_assoc])
            rw [hL, hR]
            exact Relation.EqvGen.refl _
      · -- x1 = .c2 => x2 = .a
        have hx2 : x2 = .a := by
          cases x2
          · rfl
          · exact absurd rfl h12
          · exact absurd rfl h12
        subst hx2
        cases y1
        · -- Case 7/9: (.c2 .. .a) => y2 ≠ .a
          have hy2_not_a : y2 ≠ .a := by intro he; subst he; exact hy_adj rfl
          refine ⟨?_, ?_⟩
          · rw [hsnoc_form, actARightList_snoc]
            have hnone1 : cycRedC2C3 (actAList (.c2 :: .a :: mid ++ [y2])) =
                cResidues (actAList (.c2 :: .a :: mid ++ [y2])) := by
              cases y2
              · exact absurd rfl hy2_not_a
              · exact cycRed_snoc_ac1 _ (.c2 :: .a :: mid) (by simp [actAList])
              · exact cycRed_snoc_ac2 _ (.c2 :: .a :: mid) (by simp [actAList])
            have hR := cycRed_snoc_c2a ((.c2 :: .a :: mid ++ [y2]) ++ [.a]) (.a :: mid ++ [y2])
              (by simp [List.append_assoc])
            rw [hnone1, hR]
            cases y2 <;> simp [actAList, cResidues, cResidues_append, List.append_assoc]
          · rw [hsnoc_form, actC2RightList_snoc]
            have hL := cycRed_snoc_ac2 (actCList ((.c2 :: .a :: mid ++ [y2]) ++ [.a, .c2]))
              (mid ++ [y2, .a]) (by simp [actCList, List.append_assoc])
            have hR := cycRed_snoc_c2a ((.c2 :: .a :: mid ++ [y2]) ++ [.a]) (.a :: mid ++ [y2])
              (by simp [List.append_assoc])
            rw [hL, hR]
            apply Relation.EqvGen.rel
            refine ⟨cResidues (mid ++ [y2]), [true], ?_, ?_⟩
            · cases y2 <;> simp [actCList, cResidues, cResidues_append, List.append_assoc]
            · cases y2 <;> simp [cResidues, cResidues_append, List.append_assoc]
        · -- Case 8/9: (.c2 .. .c1) => y2 = .a
          have hy2 : y2 = .a := by
            cases y2
            · rfl
            · exact absurd rfl hy_adj
            · exact absurd rfl hy_adj
          subst hy2
          refine ⟨?_, ?_⟩
          · rw [hsnoc_form, actARightList_snoc]
            have hL := cycRed_snoc_aa (actAList ((.c2 :: .a :: mid ++ [.a]) ++ [.c1, .a]))
              (.c2 :: .a :: mid ++ [.a, .c1]) (by simp [actAList, List.append_assoc])
            rw [hL]
            simp [List.append_assoc]
          · rw [hsnoc_form, actC2RightList_snoc]
            have hcL : actCList (.c2 :: .a :: mid ++ [.a]) = .a :: mid ++ [.a] := by
              simp [actCList]
            have hR := cycRed_snoc_c2c1 ((.c2 :: .a :: mid ++ [.a]) ++ [.c1])
              (.a :: mid ++ [.a]) (by simp [List.append_assoc])
            rw [hcL, hR]
            exact Relation.EqvGen.refl _
        · -- Case 9/9: (.c2 .. .c2) => y2 = .a
          have hy2 : y2 = .a := by
            cases y2
            · rfl
            · exact absurd rfl hy_adj
            · exact absurd rfl hy_adj
          subst hy2
          refine ⟨?_, ?_⟩
          · rw [hsnoc_form, actARightList_snoc]
            have hL := cycRed_snoc_aa (actAList ((.c2 :: .a :: mid ++ [.a]) ++ [.c2, .a]))
              (.c2 :: .a :: mid ++ [.a, .c2]) (by simp [actAList, List.append_assoc])
            rw [hL]
            simp [List.append_assoc]
          · rw [hsnoc_form, actC2RightList_snoc]
            have hL := cycRed_snoc_ac1 (actCList ((.c2 :: .a :: mid ++ [.a]) ++ [.c1]))
              (mid ++ [.a]) (by simp [actCList, List.append_assoc])
            have hR1 := cycRed_snoc_c2c2 ((.c2 :: .a :: mid ++ [.a]) ++ [.c2])
              (.a :: mid ++ [.a]) (by simp [List.append_assoc])
            have hR2 := cycRed_snoc_c1a (.c1 :: (.a :: mid ++ [.a]))
              (.a :: mid) (by simp)
            rw [hL, hR1, hR2]
            apply Relation.EqvGen.rel
            refine ⟨cResidues mid, [false], ?_, ?_⟩
            · simp [actCList, cResidues, cResidues_append, List.append_assoc]
            · simp [cResidues, cResidues_append]

private theorem isRotEqv_cycRed_conj_closure_aux {g : Equiv.Perm RedC2C3}
    (hg : g ∈ Subgroup.closure ({actA, actC} : Set (Equiv.Perm RedC2C3))) :
    ∀ {u : Equiv.Perm RedC2C3},
      u ∈ Subgroup.closure ({actA, actC} : Set (Equiv.Perm RedC2C3)) →
      IsRotEqv (cycRedC2C3 (evalWord (g * u * g⁻¹))) (cycRedC2C3 (evalWord u)) := by
  let H := Subgroup.closure ({actA, actC} : Set (Equiv.Perm RedC2C3))
  refine Subgroup.closure_induction ?_ ?_ ?_ ?_ hg
  · intro x hx u hu
    rcases Set.mem_insert_iff.mp hx with rfl | hx2
    · rw [evalWord_conj_actA hu, (cycRedC2C3_conjA_and_conjC (evalWord u) (u emptyRed).2).1]
      exact Relation.EqvGen.refl _
    · have hxc : x = actC := Set.mem_singleton_iff.mp hx2
      subst hxc
      rw [evalWord_conj_actC hu]
      exact (cycRedC2C3_conjA_and_conjC (evalWord u) (u emptyRed).2).2
  · intro u _; simpa using Relation.EqvGen.refl _
  · intro g1 g2 _ hg2 ih1 ih2 u hu
    have hconj : (g1 * g2) * u * (g1 * g2)⁻¹ = g1 * (g2 * u * g2⁻¹) * g1⁻¹ := by group
    rw [hconj]
    have hu2 : g2 * u * g2⁻¹ ∈ H := H.mul_mem (H.mul_mem hg2 hu) (H.inv_mem hg2)
    exact Relation.EqvGen.trans _ _ _ (ih1 hu2) (ih2 hu)
  · intro x hx ih u hu
    have hu_inv : x⁻¹ * u * (x⁻¹)⁻¹ ∈ H := H.mul_mem (H.mul_mem (H.inv_mem hx) hu) (inv_inv x ▸ hx)
    have h1 := ih hu_inv
    have hcancel : x * (x⁻¹ * u * (x⁻¹)⁻¹) * x⁻¹ = u := by group
    rw [hcancel] at h1
    exact Relation.EqvGen.symm _ _ h1

theorem isRotEqv_cycRed_conj_closure {g u : Equiv.Perm RedC2C3}
    (hg : g ∈ Subgroup.closure ({actA, actC} : Set (Equiv.Perm RedC2C3)))
    (hu : u ∈ Subgroup.closure ({actA, actC} : Set (Equiv.Perm RedC2C3))) :
    IsRotEqv (cycRedC2C3 (evalWord (g * u * g⁻¹))) (cycRedC2C3 (evalWord u)) :=
  isRotEqv_cycRed_conj_closure_aux hg hu

def adjTTChain : List Bool → ℕ
  | true :: true :: rest => 1 + adjTTChain (true :: rest)
  | _ :: rest => adjTTChain rest
  | [] => 0

def cycAdjTT : List Bool → ℕ
  | [] => 0
  | b :: bs => adjTTChain (b :: bs ++ [b])

theorem adjTTChain_split (u : List Bool) (b : Bool) (v : List Bool) :
    adjTTChain (u ++ b :: v) = adjTTChain (u ++ [b]) + adjTTChain (b :: v) := by
  induction u with
  | nil => simp [adjTTChain]
  | cons a us ih =>
      rcases us with _ | ⟨a2, us'⟩
      · cases a <;> cases b <;> simp [adjTTChain]
      · cases a <;> cases a2 <;> simp only [List.cons_append, adjTTChain] at ih ⊢ <;> omega

theorem cycAdjTT_rot_one (b : Bool) (bs : List Bool) :
    cycAdjTT (bs ++ [b]) = cycAdjTT (b :: bs) := by
  rcases bs with _ | ⟨c, cs⟩
  · rfl
  · calc cycAdjTT (c :: cs ++ [b])
        = adjTTChain ((c :: cs) ++ b :: [c]) := by simp [cycAdjTT, List.append_assoc]
      _ = adjTTChain (c :: (cs ++ [b])) + adjTTChain [b, c] := adjTTChain_split (c :: cs) b [c]
      _ = adjTTChain [b, c] + adjTTChain (c :: (cs ++ [b])) := Nat.add_comm _ _
      _ = adjTTChain ([b] ++ c :: (cs ++ [b])) := (adjTTChain_split [b] c (cs ++ [b])).symm
      _ = cycAdjTT (b :: c :: cs) := by simp [cycAdjTT]

theorem cycAdjTT_append_rot (p s : List Bool) :
    cycAdjTT (s ++ p) = cycAdjTT (p ++ s) := by
  induction p generalizing s with
  | nil => simp
  | cons a as ih =>
      have h1 : s ++ a :: as = (s ++ [a]) ++ as := by simp
      rw [h1, ih (s ++ [a])]
      simpa [List.append_assoc] using cycAdjTT_rot_one a (as ++ s)

theorem cycAdjTT_of_isRotEqv {u v : List Bool} (h : IsRotEqv u v) :
    cycAdjTT u = cycAdjTT v := by
  induction h with
  | rel _ _ hr =>
      obtain ⟨p, s, rfl, rfl⟩ := hr
      exact (cycAdjTT_append_rot p s).symm
  | refl _ => rfl
  | symm _ _ _ ih => exact ih.symm
  | trans _ _ _ _ _ ih1 ih2 => exact ih1.trans ih2

theorem actX_prepend (s : RedC2C3) (hs_not_a : ∀ rest, s.1 ≠ .a :: rest) :
    (permX s).1 = .c2 :: .a :: s.1 := by
  have h1 : actAList s.1 = .a :: s.1 := by
    rcases s with ⟨_ | ⟨x, xs⟩, _⟩
    · rfl
    · cases x
      · exact absurd rfl (hs_not_a xs)
      · rfl
      · rfl
  change actCList (actCList (actAList s.1)) = _
  rw [h1]; rfl

theorem actYInv_prepend (s : RedC2C3) (hs_not_a : ∀ rest, s.1 ≠ .a :: rest) :
    (permY⁻¹ s).1 = .c1 :: .a :: s.1 := by
  have hy_inv : permY⁻¹ = actC * actA := by
    unfold permY
    apply inv_eq_of_mul_eq_one_right
    calc (actA * actC ^ 2) * (actC * actA)
        = actA * actC ^ 3 * actA := by group
      _ = actA * actA := by rw [actC_cube, mul_one]
      _ = 1 := actA_sq
  rw [hy_inv]
  have h1 : actAList s.1 = .a :: s.1 := by
    rcases s with ⟨_ | ⟨x, xs⟩, _⟩
    · rfl
    · cases x
      · exact absurd rfl (hs_not_a xs)
      · rfl
      · rfl
  change actCList (actAList s.1) = _
  rw [h1]; rfl

theorem pow_permYInv_emptyRed (k : ℕ) :
    ((permY⁻¹ ^ k) emptyRed).1 = repL k [.c1, .a] := by
  induction k with
  | zero => rfl
  | succ m ih =>
      rw [pow_succ']
      change (permY⁻¹ ((permY⁻¹ ^ m) emptyRed)).1 = [.c1, .a] ++ repL m [.c1, .a]
      rw [actYInv_prepend]
      · rw [ih]; rfl
      · intro rest h; rw [ih] at h; cases m <;> simp [repL] at h

theorem pow_permX_on_yInv (n k : ℕ) :
    ((permX ^ n) ((permY⁻¹ ^ (k + 1)) emptyRed)).1 =
      repL n [.c2, .a] ++ repL (k + 1) [.c1, .a] := by
  induction n with
  | zero => exact pow_permYInv_emptyRed (k + 1)
  | succ m ih =>
      rw [pow_succ']
      change (permX ((permX ^ m) ((permY⁻¹ ^ (k + 1)) emptyRed))).1 = _
      rw [actX_prepend]
      · rw [ih]; rfl
      · intro rest h; rw [ih] at h; cases m <;> simp [repL] at h

theorem pow_permXYInv_on_yInv (m : ℕ) :
    (((permX * permY⁻¹) ^ m) (permY⁻¹ emptyRed)).1 =
      repL m [.c2, .a, .c1, .a] ++ [.c1, .a] := by
  induction m with
  | zero => exact pow_permYInv_emptyRed 1
  | succ k ih =>
      rw [pow_succ']
      change (permX (permY⁻¹ (((permX * permY⁻¹) ^ k) (permY⁻¹ emptyRed)))).1 = _
      have hnot1 : ∀ rest, (((permX * permY⁻¹) ^ k) (permY⁻¹ emptyRed)).1 ≠ .a :: rest := by
        intro rest h; rw [ih] at h; cases k <;> simp [repL] at h
      have hy := actYInv_prepend _ hnot1
      have hnot2 : ∀ rest, (permY⁻¹ (((permX * permY⁻¹) ^ k) (permY⁻¹ emptyRed))).1 ≠ .a :: rest := by
        intro rest h; rw [hy] at h; cases h
      rw [actX_prepend _ hnot2, hy, ih]
      rfl

theorem cResidues_repL_c2a (n : ℕ) :
    cResidues (repL n [.c2, .a]) = List.replicate n true := by
  induction n with
  | zero => rfl
  | succ k ih => simp [repL, cResidues, List.replicate_succ, ih]

theorem cResidues_repL_c1a (n : ℕ) :
    cResidues (repL n [.c1, .a]) = List.replicate n false := by
  induction n with
  | zero => rfl
  | succ k ih => simp [repL, cResidues, List.replicate_succ, ih]

theorem cResidues_repL_c2ac1a (m : ℕ) :
    cResidues (repL m [.c2, .a, .c1, .a]) = repL m [true, false] := by
  induction m with
  | zero => rfl
  | succ k ih => simp [repL, cResidues, ih]

theorem adjTTChain_rep_true_false (m : ℕ) :
    adjTTChain (repL m [true, false] ++ [false, true]) = 0 := by
  induction m with
  | zero => rfl
  | succ k ih => simp [repL, adjTTChain, ih]

theorem cycAdjTT_christoffel_zero (m : ℕ) :
    cycAdjTT (repL m [true, false] ++ [false]) = 0 := by
  rcases m with _ | k
  · rfl
  · simp only [repL, List.cons_append, cycAdjTT]
    simpa [List.append_assoc] using adjTTChain_rep_true_false k

theorem adjTTChain_replicate_true_false :
    ∀ (k : ℕ) (tail : List Bool),
      adjTTChain (List.replicate (k + 2) true ++ (false :: tail)) =
        (k + 1) + adjTTChain (false :: tail)
  | 0, tail => by simp [List.replicate, adjTTChain]
  | k + 1, tail => by
      have ih := adjTTChain_replicate_true_false k tail
      simp only [List.replicate_succ, List.cons_append, adjTTChain] at ih ⊢
      omega

theorem adjTTChain_replicate_false :
    ∀ (k : ℕ), adjTTChain (List.replicate (k + 1) false ++ [true]) = 0
  | 0 => rfl
  | k + 1 => by
      rw [List.replicate_succ, List.cons_append]
      exact adjTTChain_replicate_false k

theorem cycAdjTT_Tn_pos {n : ℕ} (hn : 2 ≤ n) :
    cycAdjTT (List.replicate n true ++ List.replicate (n + 1) false) = n - 1 := by
  obtain ⟨k, rfl⟩ : ∃ k, n = k + 2 := ⟨n - 2, by omega⟩
  have hexp : List.replicate (k + 2) true ++ List.replicate (k + 3) false =
      true :: (List.replicate (k + 1) true ++ List.replicate (k + 3) false) := rfl
  rw [hexp, cycAdjTT]
  have hlist : (true :: (List.replicate (k + 1) true ++ List.replicate (k + 3) false)) ++ [true] =
      List.replicate (k + 2) true ++ (false :: (List.replicate (k + 2) false ++ [true])) := by
    simp [List.replicate_succ, List.append_assoc]
  rw [hlist, adjTTChain_replicate_true_false k (List.replicate (k + 2) false ++ [true])]
  have hf := adjTTChain_replicate_false (k + 2)
  have hf' : adjTTChain (false :: (List.replicate (k + 2) false ++ [true])) = 0 := by
    simpa [List.replicate_succ] using hf
  omega

/-- **Theorem AK-41 (`B1`, Uncapped for ALL `n ≥ 2` including `n = 56`):** -/
theorem AK41_B1_necklace_obstruction_all_ge2 {n : ℕ} (hn : 2 ≤ n) (m : ℕ) (g : Word 2) :
    rhoC2C3 g * rhoC2C3 ((gx * gy⁻¹) ^ m * gy⁻¹) * (rhoC2C3 g)⁻¹ ≠
      rhoC2C3 (gx ^ n * (gy⁻¹) ^ (n + 1)) := by
  intro heq
  let u := rhoC2C3 ((gx * gy⁻¹) ^ m * gy⁻¹)
  let v := rhoC2C3 (gx ^ n * (gy⁻¹) ^ (n + 1))
  have hg_mem := rhoC2C3_mem_closure g
  have hu_mem := rhoC2C3_mem_closure ((gx * gy⁻¹) ^ m * gy⁻¹)
  have hrot := isRotEqv_cycRed_conj_closure hg_mem hu_mem
  rw [heq] at hrot
  have hadj_eq := cycAdjTT_of_isRotEqv hrot
  have hv_eval : evalWord v = repL n [.c2, .a] ++ repL (n + 1) [.c1, .a] := by
    unfold evalWord v
    simp only [map_mul, map_pow, map_inv, rhoC2C3_gx, rhoC2C3_gy]
    exact pow_permX_on_yInv n n
  have hv_cyc : cycRedC2C3 (evalWord v) =
      List.replicate n true ++ List.replicate (n + 1) false := by
    rw [hv_eval]
    obtain ⟨k, rfl⟩ : ∃ k, n = k + 2 := ⟨n - 2, by omega⟩
    have hnone := cycRed_snoc_c2a
      (repL (k + 2) [C2C3Syl.c2, C2C3Syl.a] ++ repL (k + 2 + 1) [C2C3Syl.c1, C2C3Syl.a])
      (.a :: repL (k + 1) [C2C3Syl.c2, C2C3Syl.a] ++ repL (k + 2) [C2C3Syl.c1, C2C3Syl.a] ++ [.c1])
      (by
        rw [repL_succ_right (k + 2) [C2C3Syl.c1, C2C3Syl.a]]
        simp [repL, List.append_assoc])
    rw [hnone, cResidues_append, cResidues_repL_c2a, cResidues_repL_c1a]
  have hu_eval : evalWord u = repL m [.c2, .a, .c1, .a] ++ [.c1, .a] := by
    unfold evalWord u
    simp only [map_mul, map_pow, map_inv, rhoC2C3_gx, rhoC2C3_gy]
    exact pow_permXYInv_on_yInv m
  have hu_cyc : cycRedC2C3 (evalWord u) = repL m [true, false] ++ [false] := by
    rw [hu_eval]
    rcases m with _ | k
    · decide
    · have hnone := cycRed_snoc_c2a
        (repL (k + 1) [C2C3Syl.c2, C2C3Syl.a, C2C3Syl.c1, C2C3Syl.a] ++ [C2C3Syl.c1, C2C3Syl.a])
        (.a :: .c1 :: .a :: repL k [C2C3Syl.c2, C2C3Syl.a, C2C3Syl.c1, C2C3Syl.a] ++ [.c1])
        (by simp [repL, List.append_assoc])
      rw [hnone, cResidues_append, cResidues_repL_c2ac1a]
      rfl
  rw [hv_cyc, hu_cyc, cycAdjTT_Tn_pos hn, cycAdjTT_christoffel_zero m] at hadj_eq
  omega

theorem AK41_B1_n56_m8_collision_resolved (g : Word 2) :
    rhoC2C3 g * rhoC2C3 ((gx * gy⁻¹) ^ 8 * gy⁻¹) * (rhoC2C3 g)⁻¹ ≠
      rhoC2C3 (gx ^ 56 * (gy⁻¹) ^ 57) :=
  AK41_B1_necklace_obstruction_all_ge2 (by decide) 8 g

end AKOneT
