/-
Copyright (c) 2019 Scott Morrison. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Scott Morrison, Justus Springer
-/
import topology.category.Top.open_nhds
import topology.sheaves.presheaf
import topology.sheaves.sheaf_condition.unique_gluing
import category_theory.adjunction.evaluation
import category_theory.limits.types
import category_theory.limits.preserves.filtered
import category_theory.limits.final
import tactic.elementwise
import algebra.category.Ring.colimits
import category_theory.sites.pushforward

/-!
# Stalks

For a presheaf `F` on a topological space `X`, valued in some category `C`, the *stalk* of `F`
at the point `x : X` is defined as the colimit of the composition of the inclusion of categories
`(nhds x)ᵒᵖ ⥤ (opens X)ᵒᵖ` and the functor `F : (opens X)ᵒᵖ ⥤ C`.
For an open neighborhood `U` of `x`, we define the map `F.germ x : F.obj (op U) ⟶ F.stalk x` as the
canonical morphism into this colimit.

Taking stalks is functorial: For every point `x : X` we define a functor `stalk_functor C x`,
sending presheaves on `X` to objects of `C`. Furthermore, for a map `f : X ⟶ Y` between
topological spaces, we define `stalk_pushforward` as the induced map on the stalks
`(f _* ℱ).stalk (f x) ⟶ ℱ.stalk x`.

Some lemmas about stalks and germs only hold for certain classes of concrete categories. A basic
property of forgetful functors of categories of algebraic structures (like `Mon`, `CommRing`,...)
is that they preserve filtered colimits. Since stalks are filtered colimits, this ensures that
the stalks of presheaves valued in these categories behave exactly as for `Type`-valued presheaves.
For example, in `germ_exist` we prove that in such a category, every element of the stalk is the
germ of a section.

Furthermore, if we require the forgetful functor to reflect isomorphisms and preserve limits (as
is the case for most algebraic structures), we have access to the unique gluing API and can prove
further properties. Most notably, in `is_iso_iff_stalk_functor_map_iso`, we prove that in such
a category, a morphism of sheaves is an isomorphism if and only if all of its stalk maps are
isomorphisms.

See also the definition of "algebraic structures" in the stacks project:
https://stacks.math.columbia.edu/tag/007L

-/

noncomputable theory

universes v u v' u'

open category_theory
open Top
open category_theory.limits
open topological_space
open opposite

variables {C : Type u} [category.{v} C]

variables [has_colimits.{v} C]

variables {X Y Z : Top.{v}}

namespace Top.presheaf

variables (C)
/-- Stalks are functorial with respect to morphisms of presheaves over a fixed `X`. -/
def stalk_functor (x : X) : X.presheaf C ⥤ C :=
((whiskering_left _ _ C).obj (open_nhds.inclusion x).op) ⋙ colim

variables {C}

/--
The stalk of a presheaf `F` at a point `x` is calculated as the colimit of the functor
nbhds x ⥤ opens F.X ⥤ C
-/
def stalk (ℱ : X.presheaf C) (x : X) : C :=
(stalk_functor C x).obj ℱ -- -- colimit ((open_nhds.inclusion x).op ⋙ ℱ)

@[simp] lemma stalk_functor_obj (ℱ : X.presheaf C) (x : X) :
  (stalk_functor C x).obj ℱ = ℱ.stalk x := rfl

/--
The germ of a section of a presheaf over an open at a point of that open.
-/
def germ (F : X.presheaf C) {U : opens X} (x : U) : F.obj (op U) ⟶ stalk F x :=
colimit.ι ((open_nhds.inclusion x.1).op ⋙ F) (op ⟨U, x.2⟩)

@[simp, elementwise]
lemma germ_res (F : X.presheaf C) {U V : opens X} (i : U ⟶ V) (x : U) :
  F.map i.op ≫ germ F x = germ F (i x : V) :=
let i' : (⟨U, x.2⟩ : open_nhds x.1) ⟶ ⟨V, (i x : V).2⟩ := i in
colimit.w ((open_nhds.inclusion x.1).op ⋙ F) i'.op

/--
A morphism from the stalk of `F` at `x` to some object `Y` is completely determined by its
composition with the `germ` morphisms.
-/
lemma stalk_hom_ext (F : X.presheaf C) {x} {Y : C} {f₁ f₂ : F.stalk x ⟶ Y}
  (ih : ∀ (U : opens X) (hxU : x ∈ U), F.germ ⟨x, hxU⟩ ≫ f₁ = F.germ ⟨x, hxU⟩ ≫ f₂) : f₁ = f₂ :=
colimit.hom_ext $ λ U, by { induction U using opposite.rec, cases U with U hxU, exact ih U hxU }

@[simp, reassoc, elementwise]
lemma stalk_functor_map_germ {F G : X.presheaf C} (U : opens X) (x : U)
  (f : F ⟶ G) : germ F x ≫ (stalk_functor C x.1).map f = f.app (op U) ≫ germ G x :=
colimit.ι_map (whisker_left ((open_nhds.inclusion x.1).op) f) (op ⟨U, x.2⟩)

variables (C)

/--
For a presheaf `F` on a space `X`, a continuous map `f : X ⟶ Y` induces a morphisms between the
stalk of `f _ * F` at `f x` and the stalk of `F` at `x`.
-/
def stalk_pushforward (f : X ⟶ Y) (F : X.presheaf C) (x : X) : (f _* F).stalk (f x) ⟶ F.stalk x :=
begin
  -- This is a hack; Lean doesn't like to elaborate the term written directly.
  transitivity,
  swap,
  exact colimit.pre _ (open_nhds.map f x).op,
  exact colim.map (whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) F),
end

@[simp, elementwise, reassoc]
lemma stalk_pushforward_germ (f : X ⟶ Y) (F : X.presheaf C) (U : opens Y)
  (x : (opens.map f).obj U) :
  (f _* F).germ ⟨f x, x.2⟩ ≫ F.stalk_pushforward C f x = F.germ x :=
begin
  rw [stalk_pushforward, germ, colimit.ι_map_assoc, colimit.ι_pre, whisker_right_app],
  erw [category_theory.functor.map_id, category.id_comp],
  refl,
end

-- Here are two other potential solutions, suggested by @fpvandoorn at
-- <https://github.com/leanprover-community/mathlib/pull/1018#discussion_r283978240>
-- However, I can't get the subsequent two proofs to work with either one.

-- def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) :
--   (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x :=
-- colim.map ((functor.associator _ _ _).inv ≫
--   whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ) ≫
-- colimit.pre ((open_nhds.inclusion x).op ⋙ ℱ) (open_nhds.map f x).op

-- def stalk_pushforward (f : X ⟶ Y) (ℱ : X.presheaf C) (x : X) :
--   (f _* ℱ).stalk (f x) ⟶ ℱ.stalk x :=
-- (colim.map (whisker_right (nat_trans.op (open_nhds.inclusion_map_iso f x).inv) ℱ) :
--   colim.obj ((open_nhds.inclusion (f x) ⋙ opens.map f).op ⋙ ℱ) ⟶ _) ≫
-- colimit.pre ((open_nhds.inclusion x).op ⋙ ℱ) (open_nhds.map f x).op

namespace stalk_pushforward
local attribute [tidy] tactic.op_induction'

@[simp] lemma id (ℱ : X.presheaf C) (x : X) :
  ℱ.stalk_pushforward C (𝟙 X) x = (stalk_functor C x).map ((pushforward.id ℱ).hom) :=
begin
  dsimp [stalk_pushforward, stalk_functor],
  ext1,
  tactic.op_induction',
  rcases j with ⟨⟨_, _⟩, _⟩,
  rw [colimit.ι_map_assoc, colimit.ι_map, colimit.ι_pre, whisker_left_app, whisker_right_app,
       pushforward.id_hom_app, eq_to_hom_map, eq_to_hom_refl],
  dsimp,
  -- FIXME A simp lemma which unfortunately doesn't fire:
  erw [category_theory.functor.map_id],
end

-- This proof is sadly not at all robust:
-- having to use `erw` at all is a bad sign.
@[simp] lemma comp (ℱ : X.presheaf C) (f : X ⟶ Y) (g : Y ⟶ Z) (x : X) :
  ℱ.stalk_pushforward C (f ≫ g) x =
  ((f _* ℱ).stalk_pushforward C g (f x)) ≫ (ℱ.stalk_pushforward C f x) :=
begin
  dsimp [stalk_pushforward, stalk_functor],
  ext U,
  induction U using opposite.rec,
  rcases U with ⟨⟨_, _⟩, _⟩,
  simp only [colimit.ι_map_assoc, colimit.ι_pre_assoc,
             whisker_right_app, category.assoc],
  dsimp,
  -- FIXME: Some of these are simp lemmas, but don't fire successfully:
  erw [category_theory.functor.map_id, category.id_comp, category.id_comp, category.id_comp,
       colimit.ι_pre, colimit.ι_pre],
  refl,
end

lemma stalk_pushforward_iso_of_open_embedding {f : X ⟶ Y} (hf : open_embedding f)
   (F : X.presheaf C) (x : X) : is_iso (F.stalk_pushforward _ f x) :=
 begin
   haveI := functor.initial_of_adjunction (hf.is_open_map.adjunction_nhds x),
   convert is_iso.of_iso ((functor.final.colimit_iso (hf.is_open_map.functor_nhds x).op
     ((open_nhds.inclusion (f x)).op ⋙ f _* F) : _).symm ≪≫ colim.map_iso _),
   swap,
   { fapply nat_iso.of_components,
     { intro U,
       refine F.map_iso (eq_to_iso _),
       dsimp only [functor.op],
       exact congr_arg op (opens.ext $ set.preimage_image_eq (unop U).1.1 hf.inj) },
     { intros U V i, erw [← F.map_comp, ← F.map_comp], congr } },
   { ext U,
     rw ← iso.comp_inv_eq,
     erw colimit.ι_map_assoc,
     rw [colimit.ι_pre, category.assoc],
     erw [colimit.ι_map_assoc, colimit.ι_pre, ← F.map_comp_assoc],
     apply colimit.w ((open_nhds.inclusion (f x)).op ⋙ f _* F) _,
     dsimp only [functor.op],
     refine ((hom_of_le _).op : op (unop U) ⟶ _),
     exact set.image_preimage_subset _ _ },
 end

end stalk_pushforward

section stalk_pullback

/-- The morphism `ℱ_{f x} ⟶ (f⁻¹ℱ)ₓ` that factors through `(f_*f⁻¹ℱ)_{f x}`. -/
def stalk_pullback_hom (f : X ⟶ Y) (F : Y.presheaf C) (x : X) :
  F.stalk (f x) ⟶ (pullback_obj f F).stalk x :=
(stalk_functor _ (f x)).map ((pushforward_pullback_adjunction C f).unit.app F) ≫
  stalk_pushforward _ _ _ x

/-- The morphism `(f⁻¹ℱ)(U) ⟶ ℱ_{f(x)}` for some `U ∋ x`. -/
def germ_to_pullback_stalk (f : X ⟶ Y) (F : Y.presheaf C) (U : opens X) (x : U) :
  (pullback_obj f F).obj (op U) ⟶ F.stalk (f x) :=
colimit.desc (Lan.diagram (opens.map f).op F (op U))
{ X := F.stalk (f x),
  ι := { app := λ V, F.germ ⟨f x, V.hom.unop.le x.2⟩,
          naturality' := λ _ _ i, by { erw category.comp_id, exact F.germ_res i.left.unop _ } } }

/-- The morphism `(f⁻¹ℱ)ₓ ⟶ ℱ_{f(x)}`. -/
def stalk_pullback_inv (f : X ⟶ Y) (F : Y.presheaf C) (x : X) :
  (pullback_obj f F).stalk x ⟶ F.stalk (f x) :=
colimit.desc ((open_nhds.inclusion x).op ⋙ presheaf.pullback_obj f F)
{ X := F.stalk (f x),
  ι := { app := λ U, F.germ_to_pullback_stalk _ f (unop U).1 ⟨x, (unop U).2⟩,
          naturality' := λ _ _ _, by { erw [colimit.pre_desc, category.comp_id], congr } } }

/-- The isomorphism `ℱ_{f(x)} ≅ (f⁻¹ℱ)ₓ`. -/
def stalk_pullback_iso (f : X ⟶ Y) (F : Y.presheaf C) (x : X) :
  F.stalk (f x) ≅ (pullback_obj f F).stalk x :=
{ hom := stalk_pullback_hom _ _ _ _,
  inv := stalk_pullback_inv _ _ _ _,
  hom_inv_id' :=
  begin
    delta stalk_pullback_hom stalk_pullback_inv stalk_functor presheaf.pullback stalk_pushforward
      germ_to_pullback_stalk germ,
    ext j,
    induction j using opposite.rec,
    cases j,
    simp only [topological_space.open_nhds.inclusion_map_iso_inv, whisker_right_app,
      whisker_left_app, whiskering_left_obj_map, functor.comp_map, colimit.ι_map_assoc,
      nat_trans.op_id, Lan_obj_map, pushforward_pullback_adjunction_unit_app_app, category.assoc,
      colimit.ι_pre_assoc],
    erw [colimit.ι_desc, colimit.pre_desc, colimit.ι_desc, category.comp_id],
    simpa
  end,
  inv_hom_id' :=
  begin
    delta stalk_pullback_hom stalk_pullback_inv stalk_functor presheaf.pullback stalk_pushforward,
    ext U j,
    induction U using opposite.rec,
    cases U, cases j, rcases j_right with ⟨⟨⟩⟩,
    erw [colimit.map_desc, colimit.map_desc, colimit.ι_desc_assoc,
      colimit.ι_desc_assoc, colimit.ι_desc, category.comp_id],
    simp only [cocone.whisker_ι, colimit.cocone_ι, open_nhds.inclusion_map_iso_inv,
      cocones.precompose_obj_ι, whisker_right_app, whisker_left_app, nat_trans.comp_app,
      whiskering_left_obj_map, nat_trans.op_id, Lan_obj_map,
      pushforward_pullback_adjunction_unit_app_app],
    erw ←colimit.w _
      (@hom_of_le (open_nhds x) _
         ⟨_, U_property⟩ ⟨(opens.map f).obj (unop j_left), j_hom.unop.le U_property⟩
         j_hom.unop.le).op,
    erw colimit.ι_pre_assoc (Lan.diagram _ F _) (costructured_arrow.map _),
    erw colimit.ι_pre_assoc (Lan.diagram _ F _) (costructured_arrow.map _),
    congr,
    simp only [category.assoc, costructured_arrow.map_mk],
    delta costructured_arrow.mk,
    congr,
  end }

end stalk_pullback

section stalk_specializes

variables {C}

/-- If `x` specializes to `y`, then there is a natural map `F.stalk y ⟶ F.stalk x`. -/
noncomputable
def stalk_specializes (F : X.presheaf C) {x y : X} (h : x ⤳ y) : F.stalk y ⟶ F.stalk x :=
begin
  refine colimit.desc _ ⟨_,λ U, _,_⟩,
  { exact colimit.ι ((open_nhds.inclusion x).op ⋙ F)
      (op ⟨(unop U).1, (specializes_iff_forall_open.mp h _ (unop U).1.2 (unop U).2 : _)⟩) },
  { intros U V i,
    dsimp,
    rw category.comp_id,
    let U' : open_nhds x := ⟨_, (specializes_iff_forall_open.mp h _ (unop U).1.2 (unop U).2 : _)⟩,
    let V' : open_nhds x := ⟨_, (specializes_iff_forall_open.mp h _ (unop V).1.2 (unop V).2 : _)⟩,
    exact colimit.w ((open_nhds.inclusion x).op ⋙ F) (show V' ⟶ U', from i.unop).op }
end

@[simp, reassoc, elementwise]
lemma germ_stalk_specializes (F : X.presheaf C) {U : opens X} {y : U} {x : X} (h : x ⤳ y) :
  F.germ y ≫ F.stalk_specializes h =
    F.germ (⟨x, h.mem_open U.is_open y.prop⟩ : U) := colimit.ι_desc _ _

@[simp, reassoc, elementwise]
lemma germ_stalk_specializes' (F : X.presheaf C) {U : opens X} {x y : X} (h : x ⤳ y) (hy : y ∈ U) :
  F.germ ⟨y, hy⟩ ≫ F.stalk_specializes h =
    F.germ ⟨x, h.mem_open U.is_open hy⟩ := colimit.ι_desc _ _

@[simp]
lemma stalk_specializes_refl {C : Type*} [category C] [limits.has_colimits C]
  {X : Top} (F : X.presheaf C) (x : X) :
  F.stalk_specializes (specializes_refl x) = 𝟙 _ :=
F.stalk_hom_ext $ λ _ _, by { dsimp, simpa }

@[simp, reassoc, elementwise]
lemma stalk_specializes_comp {C : Type*} [category C] [limits.has_colimits C]
  {X : Top} (F : X.presheaf C)
  {x y z : X} (h : x ⤳ y) (h' : y ⤳ z) :
  F.stalk_specializes h' ≫ F.stalk_specializes h = F.stalk_specializes (h.trans h') :=
F.stalk_hom_ext $ λ _ _, by simp

@[simp, reassoc, elementwise]
lemma stalk_specializes_stalk_functor_map {F G : X.presheaf C} (f : F ⟶ G) {x y : X} (h : x ⤳ y) :
  F.stalk_specializes h ≫ (stalk_functor C x).map f =
    (stalk_functor C y).map f ≫ G.stalk_specializes h :=
by { ext, delta stalk_functor, simpa [stalk_specializes] }

@[simp, reassoc, elementwise]
lemma stalk_specializes_stalk_pushforward (f : X ⟶ Y) (F : X.presheaf C) {x y : X} (h : x ⤳ y) :
  (f _* F).stalk_specializes (f.map_specializes h) ≫ F.stalk_pushforward _ f x =
    F.stalk_pushforward _ f y ≫ F.stalk_specializes h :=
by { ext, delta stalk_pushforward, simpa [stalk_specializes] }

/-- The stalks are isomorphic on inseparable points -/
@[simps]
def stalk_congr {X : Top} {C : Type*} [category C] [has_colimits C]
  (F : X.presheaf C) {x y : X}
  (e : inseparable x y) : F.stalk x ≅ F.stalk y :=
⟨F.stalk_specializes e.ge, F.stalk_specializes e.le, by simp, by simp⟩

end stalk_specializes

section concrete

variables {C}
variables [concrete_category.{v} C]

local attribute [instance] concrete_category.has_coe_to_sort concrete_category.has_coe_to_fun

@[ext]
lemma germ_ext (F : X.presheaf C) {U V : opens X} {x : X} {hxU : x ∈ U} {hxV : x ∈ V}
  (W : opens X) (hxW : x ∈ W) (iWU : W ⟶ U) (iWV : W ⟶ V) {sU : F.obj (op U)} {sV : F.obj (op V)}
  (ih : F.map iWU.op sU = F.map iWV.op sV) :
  F.germ ⟨x, hxU⟩ sU = F.germ ⟨x, hxV⟩ sV :=
by erw [← F.germ_res iWU ⟨x, hxW⟩,
    ← F.germ_res iWV ⟨x, hxW⟩, comp_apply, comp_apply, ih]

variables [preserves_filtered_colimits (forget C)]

/--
For presheaves valued in a concrete category whose forgetful functor preserves filtered colimits,
every element of the stalk is the germ of a section.
-/
lemma germ_exist (F : X.presheaf C) (x : X) (t : stalk F x) :
  ∃ (U : opens X) (m : x ∈ U) (s : F.obj (op U)), F.germ ⟨x, m⟩ s = t :=
begin
  obtain ⟨U, s, e⟩ := types.jointly_surjective.{v v} _
    (is_colimit_of_preserves (forget C) (colimit.is_colimit _)) t,
  revert s e,
  rw [(show U = op (unop U), from rfl)],
  generalize : unop U = V, clear U,
  cases V with V m,
  intros s e,
  exact ⟨V, m, s, e⟩,
end

lemma germ_eq (F : X.presheaf C) {U V : opens X} (x : X) (mU : x ∈ U) (mV : x ∈ V)
  (s : F.obj (op U)) (t : F.obj (op V))
  (h : germ F ⟨x, mU⟩ s = germ F ⟨x, mV⟩ t) :
  ∃ (W : opens X) (m : x ∈ W) (iU : W ⟶ U) (iV : W ⟶ V), F.map iU.op s = F.map iV.op t :=
begin
  obtain ⟨W, iU, iV, e⟩ := (types.filtered_colimit.is_colimit_eq_iff.{v v} _
    (is_colimit_of_preserves _ (colimit.is_colimit ((open_nhds.inclusion x).op ⋙ F)))).mp h,
  exact ⟨(unop W).1, (unop W).2, iU.unop, iV.unop, e⟩,
end

lemma stalk_functor_map_injective_of_app_injective {F G : presheaf C X} (f : F ⟶ G)
  (h : ∀ U : opens X, function.injective (f.app (op U))) (x : X) :
  function.injective ((stalk_functor C x).map f) := λ s t hst,
begin
  rcases germ_exist F x s with ⟨U₁, hxU₁, s, rfl⟩,
  rcases germ_exist F x t with ⟨U₂, hxU₂, t, rfl⟩,
  simp only [stalk_functor_map_germ_apply _ ⟨x,_⟩] at hst,
  obtain ⟨W, hxW, iWU₁, iWU₂, heq⟩ := G.germ_eq x hxU₁ hxU₂ _ _ hst,
  rw [← comp_apply, ← comp_apply, ← f.naturality, ← f.naturality, comp_apply, comp_apply] at heq,
  replace heq := h W heq,
  convert congr_arg (F.germ ⟨x,hxW⟩) heq,
  exacts [(F.germ_res_apply iWU₁ ⟨x,hxW⟩ s).symm,
          (F.germ_res_apply iWU₂ ⟨x,hxW⟩ t).symm],
end

variables [has_limits C] [preserves_limits (forget C)] [reflects_isomorphisms (forget C)]

/--
Let `F` be a sheaf valued in a concrete category, whose forgetful functor reflects isomorphisms,
preserves limits and filtered colimits. Then two sections who agree on every stalk must be equal.
-/
lemma section_ext (F : sheaf C X) (U : opens X) (s t : F.1.obj (op U))
  (h : ∀ x : U, F.presheaf.germ x s = F.presheaf.germ x t) :
  s = t :=
begin
  -- We use `germ_eq` and the axiom of choice, to pick for every point `x` a neighbourhood
  -- `V x`, such that the restrictions of `s` and `t` to `V x` coincide.
  choose V m i₁ i₂ heq using λ x : U, F.presheaf.germ_eq x.1 x.2 x.2 s t (h x),
  -- Since `F` is a sheaf, we can prove the equality locally, if we can show that these
  -- neighborhoods form a cover of `U`.
  apply F.eq_of_locally_eq' V U i₁,
  { intros x hxU,
    rw [opens.mem_supr],
    exact ⟨⟨x, hxU⟩, m ⟨x, hxU⟩⟩ },
  { intro x,
    rw [heq, subsingleton.elim (i₁ x) (i₂ x)] }
end

/-
Note that the analogous statement for surjectivity is false: Surjectivity on stalks does not
imply surjectivity of the components of a sheaf morphism. However it does imply that the morphism
is an epi, but this fact is not yet formalized.
-/
lemma app_injective_of_stalk_functor_map_injective {F : sheaf C X} {G : presheaf C X}
  (f : F.1 ⟶ G) (U : opens X) (h : ∀ x : U, function.injective ((stalk_functor C x.val).map f)) :
  function.injective (f.app (op U)) :=
λ s t hst, section_ext F _ _ _ $ λ x, h x $ by
  rw [stalk_functor_map_germ_apply, stalk_functor_map_germ_apply, hst]

lemma app_injective_iff_stalk_functor_map_injective {F : sheaf C X}
  {G : presheaf C X} (f : F.1 ⟶ G) :
  (∀ x : X, function.injective ((stalk_functor C x).map f)) ↔
  (∀ U : opens X, function.injective (f.app (op U))) :=
⟨λ h U, app_injective_of_stalk_functor_map_injective f U (λ x, h x.1),
  stalk_functor_map_injective_of_app_injective f⟩

instance stalk_functor_preserves_mono (x : X) :
  functor.preserves_monomorphisms (sheaf.forget C X ⋙ stalk_functor C x) :=
⟨λ 𝓐 𝓑 f m, concrete_category.mono_of_injective _ $
  (app_injective_iff_stalk_functor_map_injective f.1).mpr
    (λ c, (@@concrete_category.mono_iff_injective_of_preserves_pullback _ _ (f.1.app (op c)) _).mp
      ((nat_trans.mono_iff_mono_app _ f.1).mp
        (@@category_theory.presheaf_mono_of_mono _ _ _ _ _ _ _ _ _ _ _ m) $ op c)) x⟩

lemma stalk_mono_of_mono {F G : sheaf C X} (f : F ⟶ G) [mono f] :
  Π x, mono $ (stalk_functor C x).map f.1 :=
λ x, by convert functor.map_mono (sheaf.forget.{v} C X ⋙ stalk_functor C x) f

lemma mono_of_stalk_mono {F G : sheaf C X} (f : F ⟶ G)
  [Π x, mono $ (stalk_functor C x).map f.1] : mono f :=
(Sheaf.hom.mono_iff_presheaf_mono _ _ _).mpr $ (nat_trans.mono_iff_mono_app _ _).mpr $ λ U,
  (concrete_category.mono_iff_injective_of_preserves_pullback _).mpr $
  app_injective_of_stalk_functor_map_injective f.1 U.unop $ λ ⟨x, hx⟩,
  (concrete_category.mono_iff_injective_of_preserves_pullback _).mp $ infer_instance

/-- For surjectivity, we are given an arbitrary section `t` and need to find a preimage for it.
We claim that it suffices to find preimages *locally*. That is, for each `x : U` we construct
a neighborhood `V ≤ U` and a section `s : F.obj (op V))` such that `f.app (op V) s` and `t`
agree on `V`. -/
lemma app_surjective_of_injective_of_locally_surjective {F G : sheaf C X} (f : F ⟶ G)
  (U : opens X) (hinj : ∀ x : U, function.injective ((stalk_functor C x.1).map f.1))
  (hsurj : ∀ (t) (x : U), ∃ (V : opens X) (m : x.1 ∈ V) (iVU : V ⟶ U) (s : F.1.obj (op V)),
    f.1.app (op V) s = G.1.map iVU.op t) :
  function.surjective (f.1.app (op U)) :=
begin
  intro t,
  -- We use the axiom of choice to pick around each point `x` an open neighborhood `V` and a
  -- preimage under `f` on `V`.
  choose V mV iVU sf heq using hsurj t,
  -- These neighborhoods clearly cover all of `U`.
  have V_cover : U ≤ supr V,
  { intros x hxU,
    rw [opens.mem_supr],
    exact ⟨⟨x, hxU⟩, mV ⟨x, hxU⟩⟩ },
  -- Since `F` is a sheaf, we can glue all the local preimages together to get a global preimage.
  obtain ⟨s, s_spec, -⟩ := F.exists_unique_gluing' V U iVU V_cover sf _,
  { use s,
    apply G.eq_of_locally_eq' V U iVU V_cover,
    intro x,
    rw [← comp_apply, ← f.1.naturality, comp_apply, s_spec, heq] },
  { intros x y,
    -- What's left to show here is that the secions `sf` are compatible, i.e. they agree on
    -- the intersections `V x ⊓ V y`. We prove this by showing that all germs are equal.
    apply section_ext,
    intro z,
    -- Here, we need to use injectivity of the stalk maps.
    apply (hinj ⟨z, (iVU x).le ((inf_le_left : V x ⊓ V y ≤ V x) z.2)⟩),
    dsimp only,
    erw [stalk_functor_map_germ_apply, stalk_functor_map_germ_apply],
    simp_rw [← comp_apply, f.1.naturality, comp_apply, heq, ← comp_apply, ← G.1.map_comp],
    refl }
end

lemma app_surjective_of_stalk_functor_map_bijective {F G : sheaf C X} (f : F ⟶ G)
  (U : opens X) (h : ∀ x : U, function.bijective ((stalk_functor C x.val).map f.1)) :
  function.surjective (f.1.app (op U)) :=
begin
  refine app_surjective_of_injective_of_locally_surjective f U (λ x, (h x).1) (λ t x, _),
  -- Now we need to prove our initial claim: That we can find preimages of `t` locally.
  -- Since `f` is surjective on stalks, we can find a preimage `s₀` of the germ of `t` at `x`
  obtain ⟨s₀,hs₀⟩ := (h x).2 (G.presheaf.germ x t),
  -- ... and this preimage must come from some section `s₁` defined on some open neighborhood `V₁`
  obtain ⟨V₁,hxV₁,s₁,hs₁⟩ := F.presheaf.germ_exist x.1 s₀,
  subst hs₁, rename hs₀ hs₁,
  erw stalk_functor_map_germ_apply V₁ ⟨x.1,hxV₁⟩ f.1 s₁ at hs₁,
  -- Now, the germ of `f.app (op V₁) s₁` equals the germ of `t`, hence they must coincide on
  -- some open neighborhood `V₂`.
  obtain ⟨V₂, hxV₂, iV₂V₁, iV₂U, heq⟩ := G.presheaf.germ_eq x.1 hxV₁ x.2 _ _ hs₁,
  -- The restriction of `s₁` to that neighborhood is our desired local preimage.
  use [V₂, hxV₂, iV₂U, F.1.map iV₂V₁.op s₁],
  rw [← comp_apply, f.1.naturality, comp_apply, heq],
end

lemma app_bijective_of_stalk_functor_map_bijective {F G : sheaf C X} (f : F ⟶ G)
   (U : opens X) (h : ∀ x : U, function.bijective ((stalk_functor C x.val).map f.1)) :
  function.bijective (f.1.app (op U)) :=
⟨app_injective_of_stalk_functor_map_injective f.1 U (λ x, (h x).1),
  app_surjective_of_stalk_functor_map_bijective f U h⟩

lemma app_is_iso_of_stalk_functor_map_iso {F G : sheaf C X} (f : F ⟶ G) (U : opens X)
  [∀ x : U, is_iso ((stalk_functor C x.val).map f.1)] : is_iso (f.1.app (op U)) :=
begin
  -- Since the forgetful functor of `C` reflects isomorphisms, it suffices to see that the
  -- underlying map between types is an isomorphism, i.e. bijective.
  suffices : is_iso ((forget C).map (f.1.app (op U))),
  { exactI is_iso_of_reflects_iso (f.1.app (op U)) (forget C) },
  rw is_iso_iff_bijective,
  apply app_bijective_of_stalk_functor_map_bijective,
  intro x,
  apply (is_iso_iff_bijective _).mp,
  exact functor.map_is_iso (forget C) ((stalk_functor C x.1).map f.1)
end

/--
Let `F` and `G` be sheaves valued in a concrete category, whose forgetful functor reflects
isomorphisms, preserves limits and filtered colimits. Then if the stalk maps of a morphism
`f : F ⟶ G` are all isomorphisms, `f` must be an isomorphism.
-/
-- Making this an instance would cause a loop in typeclass resolution with `functor.map_is_iso`
lemma is_iso_of_stalk_functor_map_iso {F G : sheaf C X} (f : F ⟶ G)
  [∀ x : X, is_iso ((stalk_functor C x).map f.1)] : is_iso f :=
begin
  -- Since the inclusion functor from sheaves to presheaves is fully faithful, it suffices to
  -- show that `f`, as a morphism between _presheaves_, is an isomorphism.
  suffices : is_iso ((sheaf.forget C X).map f),
  { exactI is_iso_of_fully_faithful (sheaf.forget C X) f },
  -- We show that all components of `f` are isomorphisms.
  suffices : ∀ U : (opens X)ᵒᵖ, is_iso (f.1.app U),
  { exact @nat_iso.is_iso_of_is_iso_app _ _ _ _ F.1 G.1 f.1 this, },
  intro U, induction U using opposite.rec,
  apply app_is_iso_of_stalk_functor_map_iso
end

/--
Let `F` and `G` be sheaves valued in a concrete category, whose forgetful functor reflects
isomorphisms, preserves limits and filtered colimits. Then a morphism `f : F ⟶ G` is an
isomorphism if and only if all of its stalk maps are isomorphisms.
-/
lemma is_iso_iff_stalk_functor_map_iso {F G : sheaf C X} (f : F ⟶ G) :
  is_iso f ↔ ∀ x : X, is_iso ((stalk_functor C x).map f.1) :=
begin
  split,
  { intros h x, resetI,
    exact @functor.map_is_iso _ _ _ _ _ _ (stalk_functor C x) f.1
      ((sheaf.forget C X).map_is_iso f) },
  { intro h,
    exactI is_iso_of_stalk_functor_map_iso f }
end

end concrete

instance (F : X.presheaf CommRing) {U : opens X} (x : U) :
  algebra (F.obj $ op U) (F.stalk x) :=
(F.germ x).to_algebra

@[simp]
lemma stalk_open_algebra_map {X : Top} (F : X.presheaf CommRing) {U : opens X} (x : U) :
  algebra_map (F.obj $ op U) (F.stalk x) = F.germ x := rfl

end Top.presheaf


import category_theory.abelian.basic
import category_theory.preadditive.additive_functor
import for_mathlib.short_exact_sequence
import for_mathlib.abelian_category
import for_mathlib.exact_lift_desc

/-!

Refs:
1. Grothendieck's Tôhoku paper
2. Stacks tag 010T

-/

noncomputable theory
namespace category_theory

universes v v' u u'
variables (A : Type u) (B : Type u')
  [category.{v} A] [category.{v} B] [abelian A] [abelian B]

/-- Cohomological covariant delta functor. -/
@[nolint has_inhabited_instance]
structure delta_functor :=
(F : ℕ → A ⥤ B)
[additive : ∀ n, functor.additive (F n)]
(δ : Π (n : ℕ),
  short_exact_sequence.Trd A ⋙ (F n) ⟶ short_exact_sequence.Fst A ⋙ (F (n+1)))
(mono : ∀ (S : short_exact_sequence _), mono ((F 0).map S.f))
(exact' : ∀ (n : ℕ) (S : short_exact_sequence _), exact ((F n).map S.f) ((F n).map S.g))
(exact_δ : ∀ (n : ℕ) (S : short_exact_sequence _),
  exact ((F n).map S.g) ((δ n).app S))
(δ_exact : ∀ (n : ℕ) (S : short_exact_sequence _),
  exact ((δ n).app S) ((F (n+1)).map S.f))

namespace delta_functor

infixr ` ⥤δ `:26 := delta_functor

instance : has_coe_to_fun (A ⥤δ B) (λ F, ℕ → (A ⥤ B)) := ⟨F⟩

instance additive_apply (F : A ⥤δ B) (n : ℕ) :
  functor.additive (F n) := F.additive n

variables {A B}

/-- Morphisms of cohomological covariant delta functors. -/
@[nolint has_inhabited_instance]
structure hom (F G : A ⥤δ B) :=
(η : Π n, F n ⟶ G n)
(comm' : ∀ n, F.δ n ≫ whisker_left _ (η _) = whisker_left _ (η _) ≫ G.δ _)

instance : quiver (A ⥤δ B) :=
{ hom := hom }

namespace hom

instance {F G : A ⥤δ B} : has_coe_to_fun (F ⟶ G) (λ η, Π n, F n ⟶ G n) :=
⟨η⟩

@[ext]
lemma ext {F G : A ⥤δ B} (η γ : F ⟶ G) (h : ∀ n, η n = γ n) : η = γ :=
by { cases η, cases γ, congr, ext1, apply h }

@[simp]
lemma η_eq_coe {F G : A ⥤δ B} (η : F ⟶ G) (n : ℕ) :
  η.η n = η n := rfl

@[simp, reassoc]
lemma comm {F G : A ⥤δ B} (η : F ⟶ G) (n : ℕ) (S : short_exact_sequence A) :
  (F.δ n).app S ≫ (η (n+1)).app S.fst =
  (η n).app S.trd ≫ (G.δ n).app S :=
begin
  have := η.comm' n,
  apply_fun (λ e, e.app S) at this,
  exact this,
end

/-- Identity morphisms of delta functors. -/
def id (F : A ⥤δ B) : F ⟶ F :=
⟨λ n, 𝟙 _, begin
  intros n,
  ext, dsimp,
  erw nat_trans.id_app,
  erw nat_trans.id_app,
  simp,
end⟩

@[simp]
lemma id_apply (F : A ⥤δ B) (n : ℕ) :
  id F n = 𝟙 _ := rfl

/-- Compositions of morphisms of delta functors. -/
def comp {F G H : A ⥤δ B} (η : F ⟶ G) (γ : G ⟶ H) :
  hom F H :=
{ η := λ n, η n ≫ γ n,
  comm' := begin
    intros n, ext,
    dsimp,
    simp,
  end }

@[simp]
lemma comp_apply {F G H : A ⥤δ B} (η : F ⟶ G) (γ : G ⟶ H) (n : ℕ) :
  (hom.comp η γ) n = η n ≫ γ n := rfl

end hom

/-- delta functors form a category. -/
instance category : category (A ⥤δ B) :=
{ id := λ F, hom.id _,
  comp := λ X Y Z F G, hom.comp F G,
  id_comp' := by { intros F G f, ext, dsimp, simp },
  comp_id' := by { intros F G f, ext, dsimp, simp },
  assoc' := by { intros F G H W a b c, ext, dsimp, simp },
  ..(infer_instance : quiver (A ⥤δ B)) }

/-- Universal delta functors. -/
class universal (F : A ⥤δ B) : Prop :=
(cond : ∀ (G : A ⥤δ B) (e0 : F 0 ⟶ G 0), ∃! e : F ⟶ G, (e : Π n, F n ⟶ G n) 0 = e0)

namespace tohoku

/-- An effacement relative to a δ functor. -/
@[nolint has_inhabited_instance]
structure effacement (F : A ⥤δ B) (X : A) (n : ℕ) :=
(I : A)
(ι : X ⟶ I)
[mono : category_theory.mono ι]
(w : (F (n+1)).map ι = 0)

/-- Morphisms between effacements. -/
@[ext, nolint has_inhabited_instance]
structure effacement.hom (F : A ⥤δ B) (X : A) (n : ℕ)
  (e₁ e₂ : effacement F X n) :=
(t : e₁.I ⟶ e₂.I)
(w : e₁.ι ≫ t = e₂.ι)

instance effacement.category (F : A ⥤δ B) (X : A) (n : ℕ) :
  category (effacement F X n) :=
{ hom := λ e₁ e₂, e₁.hom _ _ _ e₂,
  id := λ e, ⟨𝟙 _, category.comp_id _⟩,
  comp := λ a b c f g, ⟨f.t ≫ g.t, by simp [reassoc_of f.w, g.w]⟩,
  id_comp' := λ a b f, effacement.hom.ext _ _ $ category.id_comp _,
  comp_id' := λ a b f, effacement.hom.ext _ _ $ category.comp_id _,
  assoc' := λ a b c d f g h,
    effacement.hom.ext _ _ $ category.assoc _ _ _ }

instance effacement_mono (F : A ⥤δ B) (X : A) (n : ℕ)
  (e : effacement F X n) : category_theory.mono e.ι := e.mono

/-- Effacable δ functors. -/
class effaceable (F : A ⥤δ B) : Prop :=
(cond [] : ∀ (X : A) (n : ℕ), nonempty (effacement F X n))

/-- A choice of effacement. -/
def choose_effacement (F : A ⥤δ B) [effaceable F] (X : A) (n : ℕ) : effacement F X n :=
(effaceable.cond F X n).some

/-- A short exact sequence associated to an effacement -/
def effacement.ses {F : A ⥤δ B} {X n} (e : effacement F X n) : short_exact_sequence A :=
{ fst := X,
  snd := e.I,
  trd := limits.cokernel e.ι,
  f := e.ι,
  g := limits.cokernel.π _,
  exact' := abelian.exact_cokernel e.ι }

/-- An auxiliary definition used to obtain the isomorphism below -/
def effacement.cokernel_comparison {F : A ⥤δ B} {X n} (e : effacement F X n) :
  limits.cokernel ((F n).map (limits.cokernel.π e.ι)) ⟶ (F (n+1)).obj X :=
limits.cokernel.desc _ ((F.δ n).app e.ses) (F.exact_δ n e.ses).w

open_locale zero_object
instance effacement.epi_cokernel_comparison {F : A ⥤δ B} {X n} (e : effacement F X n) :
  epi e.cokernel_comparison :=
begin
  dsimp [effacement.cokernel_comparison],
  let t := _, change epi t,
  suffices : epi (limits.cokernel.π _ ≫ t),
  { resetI,
    apply epi_of_epi (limits.cokernel.π _) t },
  simp only [limits.cokernel.π_desc],
  have : exact ((F.δ n).app e.ses) ((F (n+1)).map e.ι) :=
    F.δ_exact n e.ses,
  rw e.w at this,

  apply abelian.pseudoelement.epi_of_pseudo_surjective,
  intros q,
  exact (abelian.pseudoelement.pseudo_exact_of_exact this).2 q (by simp),
end

/- This is true with fewer assumptions... -/
instance effacement.mono_cokernel_comparison {F : A ⥤δ B} {X n} (e : effacement F X n) :
  category_theory.mono e.cokernel_comparison :=
begin
  dsimp [effacement.cokernel_comparison],
  let t := _, change category_theory.mono t,
  suffices : exact ((F n).map (limits.cokernel.π e.ι)) ((F.δ n).app e.ses),
  exact abelian.category_theory.limits.cokernel.desc.category_theory.mono
    ((F n).map (limits.cokernel.π e.ι))
    ((F.δ n).app (effacement.ses e)) this,
  exact F.exact_δ n e.ses,
end

instance effacement.is_iso_cokernel_comparison {F : A ⥤δ B} {X n} (e : effacement F X n) :
  is_iso e.cokernel_comparison :=
is_iso_of_mono_of_epi _

/-- The cokernel isomorphism associated to an effacement. -/
def effacement.cokernel_iso {F : A ⥤δ B} {X n} (e : effacement F X n) :
  limits.cokernel ((F n).map (limits.cokernel.π e.ι)) ≅ (F (n+1)).obj X :=
as_iso e.cokernel_comparison

@[simp, reassoc]
lemma effacement.cokernel_iso_spec {F : A ⥤δ B} {X n} (e : effacement F X n) :
  limits.cokernel.π _ ≫ e.cokernel_iso.hom =
  (F.δ n).app e.ses :=
limits.cokernel.π_desc _ _ _

/-- An auxiliary definition used in `lift` below. -/
def effacement.lift_app_aux {F G : A ⥤δ B} {X n}
  (η : F n ⟶ G n) (e : effacement F X n) :
  (F (n+1)).obj X ⟶ (G (n+1)).obj X :=
e.cokernel_iso.inv ≫
limits.cokernel.desc _
(η.app _ ≫ (G.δ n).app e.ses)
begin
  rw [← category.assoc, η.naturality, category.assoc],
  erw (G.exact_δ n e.ses).w,
  rw [limits.comp_zero]
end

/-- An auxiliary definition used in `lift` below. -/
def effacement.map_ses {F : A ⥤δ B} {X n}
  (e₁ e₂ : effacement F X n) (q : e₁ ⟶ e₂) :
  e₁.ses ⟶ e₂.ses :=
{ fst := 𝟙 _,
  snd := q.t,
  trd := begin
    refine limits.cokernel.desc _ _ _,
    refine _ ≫ limits.cokernel.π _,
    exact q.t,
    rw [← category.assoc, q.w, limits.cokernel.condition]
  end,
  sq1' := by { simp only [category.id_comp], exact q.w.symm },
  sq2' := begin
    erw limits.cokernel.π_desc,
    refl,
  end }

lemma effacement.lift_app_aux_eq_of_hom
  {F G : A ⥤δ B} {X n}
  (η : F n ⟶ G n) (e₁ e₂ : effacement F X n) (q : e₁ ⟶ e₂) :
  e₁.lift_app_aux η = e₂.lift_app_aux η :=
begin
  dsimp only [effacement.lift_app_aux],
  rw iso.inv_comp_eq,
  apply limits.coequalizer.hom_ext,
  simp only [limits.cokernel.π_desc, effacement.cokernel_iso_spec_assoc],
  rw ← category.assoc, let t := _, change _ = t ≫ _,
  have ht : t = (F n).map (e₁.map_ses e₂ q).trd ≫ limits.cokernel.π _,
  { dsimp [t], rw iso.comp_inv_eq,
    simp only [category.assoc, effacement.cokernel_iso_spec],
    erw (F.δ n).naturality (e₁.map_ses e₂ q),
    dsimp [effacement.map_ses],
    simp },
  rw ht, clear ht t,
  simp only [category.assoc, limits.cokernel.π_desc],
  erw [nat_trans.naturality_assoc],
  congr' 1,
  erw (G.δ n).naturality (e₁.map_ses e₂ q),
  symmetry,
  convert category.comp_id _,
  exact functor.map_id _ _,
end

lemma effacement.lift_app_aux_well_defined
  {F G : A ⥤δ B} {X n}
  (η : F n ⟶ G n) (e₁ e₂ : effacement F X n) :
  e₁.lift_app_aux η = e₂.lift_app_aux η :=
begin
  let II := limits.biprod e₁.I e₂.I,
  let ι : X ⟶ II := limits.biprod.lift e₁.ι e₂.ι,
  let e : effacement F X n := ⟨II, ι, _⟩, -- use additivity of `F n`.
  swap,
  { haveI : limits.preserves_binary_biproducts (F (n+1)) :=
      limits.preserves_binary_biproducts_of_preserves_biproducts (F (n + 1)),
    let E : (F (n + 1)).obj (e₁.I ⊞ e₂.I) ≅ (F (n + 1)).obj (e₁.I) ⊞ (F (n+1)).obj (e₂.I) :=
      functor.map_biprod (F (n+1)) _ _,
    rw [← cancel_mono E.hom, limits.zero_comp],
    rw functor.map_biprod_hom,
    apply limits.biprod.hom_ext,
    { simp only [category.assoc, limits.biprod.lift_fst, limits.zero_comp],
      simp only [← functor.map_comp, limits.biprod.lift_fst, e₁.w] },
    { simp only [category.assoc, limits.biprod.lift_snd, limits.zero_comp],
      simp only [← functor.map_comp, limits.biprod.lift_snd, e₂.w] } },
  let π₁ : e ⟶ e₁ := ⟨limits.biprod.fst, _⟩,
  swap, { dsimp [e], simp, },
  let π₂ : e ⟶ e₂ := ⟨limits.biprod.snd, _⟩,
  swap, { dsimp [e], simp, },
  rw ← effacement.lift_app_aux_eq_of_hom η _ _ π₁,
  rw ← effacement.lift_app_aux_eq_of_hom η _ _ π₂,
end

lemma effacement.lift_naturality
  {F G : A ⥤δ B} {X Y n}
  (η : F n ⟶ G n) (e₁ : effacement F X n) (e₂ : effacement F Y n) (f : X ⟶ Y) :
  e₁.lift_app_aux η ≫ (G (n+1)).map f =
  (F (n+1)).map f ≫ e₂.lift_app_aux η :=
begin
  let e₁' : effacement F X n :=
    ⟨limits.biprod e₁.I e₂.I, limits.biprod.lift e₁.ι (f ≫ e₂.ι), _⟩, -- again, additivity
  swap,
  { haveI : limits.preserves_binary_biproducts (F (n+1)) :=
      limits.preserves_binary_biproducts_of_preserves_biproducts (F (n + 1)),
    let E : (F (n + 1)).obj (e₁.I ⊞ e₂.I) ≅ (F (n + 1)).obj (e₁.I) ⊞ (F (n+1)).obj (e₂.I) :=
      functor.map_biprod (F (n+1)) _ _,
    rw [← cancel_mono E.hom, limits.zero_comp],
    rw functor.map_biprod_hom,
    apply limits.biprod.hom_ext,
    simp only [category.assoc, limits.biprod.lift_fst, limits.zero_comp],
    simp only [← functor.map_comp, limits.biprod.lift_fst],
    exact e₁.w,
    simp only [category.assoc, limits.biprod.lift_snd, limits.zero_comp],
    simp only [← functor.map_comp, limits.biprod.lift_snd],
    simp only [functor.map_comp, e₂.w, limits.comp_zero] },
  rw e₁.lift_app_aux_well_defined η e₁',
  dsimp [effacement.lift_app_aux],
  simp only [category.assoc, iso.inv_comp_eq],
  apply limits.coequalizer.hom_ext,
  simp only [limits.coequalizer_as_cokernel, limits.cokernel.π_desc_assoc, category.assoc],
  erw limits.cokernel.π_desc_assoc,
  let q : e₁'.ses ⟶ e₂.ses := ⟨f, limits.biprod.snd,
    limits.cokernel.desc _ (limits.biprod.snd ≫ limits.cokernel.π _) _, _, _⟩,
  erw ← (F.δ n).naturality_assoc q,
  erw ← (G.δ n).naturality q,
  dsimp,
  have : (F.δ n).app e₂.ses ≫ e₂.cokernel_iso.inv = limits.cokernel.π _,
  { rw iso.comp_inv_eq, simp, },
  rw reassoc_of this, clear this,
  simp only [category.assoc, limits.cokernel.π_desc],
  erw ← nat_trans.naturality_assoc,
  refl,
  { dsimp [e₁'],
    simp },
  { dsimp [e₁', effacement.ses],
    simp },
  { dsimp [e₁', effacement.ses], simp, },
end

lemma effacement.lift_δ_naturality
  {F G : A ⥤δ B} {n}
  (η : F n ⟶ G n) (S : short_exact_sequence A)
  (e₁ : effacement F S.fst n) (e₂ : effacement F S.snd n) :
  (F.δ n).app S ≫ e₁.lift_app_aux η =
  η.app _ ≫ (G.δ _).app S :=
begin
  let e₁' : effacement F S.fst n :=
  ⟨e₂.I, S.f ≫ e₂.ι, by simp [e₂.w]⟩,
  rw e₁.lift_app_aux_well_defined η e₁',
  let q : S ⟶ e₁'.ses :=
    ⟨𝟙 _, e₂.ι, S.exact'.epi_desc (e₂.ι ≫ limits.cokernel.π _) _, _, _⟩,
  dsimp only [effacement.lift_app_aux],
  have : (F.δ n).app S ≫ e₁'.cokernel_iso.inv = (F n).map q.trd ≫
    limits.cokernel.π _,
  { rw iso.comp_inv_eq,
    simp,
    erw (F.δ n).naturality q,
    dsimp,
    simp only [functor.map_id, category.comp_id] },
  slice_lhs 1 2
  { erw this },
  simp only [category.assoc, limits.cokernel.π_desc],
  erw η.naturality_assoc,
  congr' 1,
  erw (G.δ n).naturality q, convert category.comp_id _,
  { dsimp, simpa only [functor.map_id], },
  rw ← category.assoc, exact limits.cokernel.condition _,
  { dsimp, simpa },
  { dsimp, simpa only [exact.comp_epi_desc] }
end

/-- An auxiliary definition used in `lift` below. -/
def effaceable.lift_component (F G : A ⥤δ B) [effaceable F] (n) (η : F n ⟶ G n) :
  F (n+1) ⟶ G (n+1) :=
{ app := λ X, (choose_effacement F X n).lift_app_aux η,
  naturality' := begin
    intros X Y f,
    symmetry,
    apply effacement.lift_naturality,
  end }

/-- The lift of η0. -/
noncomputable
def effaceable.lift (F G : A ⥤δ B) [effaceable F] (η0 : F 0 ⟶ G 0) : Π n, F n ⟶ G n
| 0 := η0
| (n+1) := effaceable.lift_component _ _ _ (effaceable.lift n)

/-- The lift of η0, as an actual delta functor. -/
def effaceable.lift_with_δ (F G : A ⥤δ B) [effaceable F] (η0 : F 0 ⟶ G 0) :
  F ⟶ G :=
{ η := effaceable.lift _ _ η0,
  comm' := begin
    intros n, ext S : 2,
    dsimp,
    rcases n with (_|n),
    { dsimp [effaceable.lift],
      apply effacement.lift_δ_naturality,
      apply choose_effacement },
    { dsimp [effaceable.lift],
      apply effacement.lift_δ_naturality,
      apply choose_effacement },
  end }

lemma effaceable.lift_with_δ_unique (F G : A ⥤δ B) [effaceable F] (η0 : F 0 ⟶ G 0)
  (η : F ⟶ G) (hη : η 0 = η0) : η = effaceable.lift_with_δ F G η0 :=
begin
  ext1 n, induction n with n hn,
  { rw hη, refl },
  { ext T, dsimp [effaceable.lift_with_δ] at ⊢ hn,
    change _ = ((effaceable.lift F G η0) _).app _,
    dsimp [effaceable.lift],
    change _ = effaceable.lift F G η0 n at hn,
    erw ← hn,
    dsimp [effaceable.lift_component],
    dsimp [effacement.lift_app_aux],
    rw iso.eq_inv_comp,
    apply limits.coequalizer.hom_ext,
    dsimp,
    simp only [effacement.cokernel_iso_spec_assoc, limits.cokernel.π_desc],
    have := effacement.lift_δ_naturality (η n) ((choose_effacement F T n).ses)
      (choose_effacement _ _ _) (choose_effacement _ _ _),
    erw ← this, congr' 1,
    dsimp only [effacement.lift_app_aux],
    rw iso.eq_inv_comp,

    apply limits.coequalizer.hom_ext,
    simp only [effacement.cokernel_iso_spec_assoc, limits.cokernel.π_desc],
    clear this,
    have := η.comm' n,
    apply_fun (λ e, e.app ((choose_effacement F (choose_effacement F T n).ses.fst n).ses)) at this,
    exact this },
end

end tohoku
open tohoku

theorem universal_of_effaceable (F : A ⥤δ B) [effaceable F] : universal F :=
begin
  constructor, intros G η0,
  use effaceable.lift_with_δ F G η0,
  split,
  { ext, refl, },
  { intros η hη, apply effaceable.lift_with_δ_unique, exact hη, }
end

-- Sketch:
-- TODO: Prove stacks tag 010T. -- DONE!
-- TODO: Construct `Ext^*(-,X)` a delta functor (on objects!).
-- These should be functors `Aᵒᵖ ⥤ Ab` (assuming `A` has enough projectives).
-- Use `010T` to see that `Ext^*(-,X)` is universal.

end delta_functor

end category_theory


import data.finsupp.pointwise
import verification.semantics.stream
import verification.semantics.stream_props

noncomputable theory
open_locale classical

class Eval (α : Type*) (ι : out_param Type) (β : out_param Type*) [has_zero β] :=
(eval : α → (ι →₀ β))

instance Stream.Eval_base {ι : Type} {α : Type*} [add_zero_class α] :
  Eval (StreamExec ι α) ι α :=
{ eval := λ s, s.eval }

instance SimpleStream.Eval_base {ι : Type} {α : Type*} [linear_order ι] [add_zero_class α] :
  Eval (SimpleStream ι α) ι α :=
{ eval := λ s, Eval.eval (↑s : StreamExec ι α) }

instance Stream.Eval_ind {ι α ι' α' : Type*} [add_zero_class α'] [Eval α ι' α'] :
  Eval (StreamExec ι α) ι (ι' →₀ α') :=
{ eval := λ s, (Eval.eval <$₂> s).eval }

instance SimpleStream.Eval_ind {ι α ι' α' : Type*} [linear_order ι] [add_zero_class α'] [Eval α ι' α'] :
  Eval (SimpleStream ι α) ι (ι' →₀ α') :=
{ eval := λ s, Eval.eval (↑s : StreamExec ι α) }

class AddZeroEval (α : Type*) (ι : out_param Type) (β : out_param Type*) [add_zero_class β]
  extends Eval α ι β, has_add α, has_zero α :=
(hadd : ∀ (x y : α), eval (x + y) = eval x + eval y)
(hzero : eval 0 = 0)

class MulEval (α : Type*) (ι : out_param Type) (β : out_param Type*) [non_unital_non_assoc_semiring β]
  extends Eval α ι β, has_mul α :=
(hmul : ∀ (x y : α), eval (x * y) = eval x * eval y)

attribute [simp] AddZeroEval.hadd AddZeroEval.hzero
  MulEval.hmul

@[simp] lemma Eval.contract {ι ι' : Type} {α α' : Type*} [add_comm_monoid α'] [Eval α ι' α']
  (s : StreamExec ι α) :
  Eval.eval (contract_stream s) () = (Eval.eval s).sum_range :=
by simp [Eval.eval, contract_stream, StreamExec.bimap_bimap, ← contract_stream_spec_apply]

@[simp] lemma Eval.contract' {ι ι' : Type} {α α' : Type*} [linear_order ι] [add_comm_monoid α'] [Eval α ι' α']
  (s : SimpleStream ι α) :
  Eval.eval s.contract () = (Eval.eval s).sum_range :=
Eval.contract _


import .functor
import .for_mathlib.coprod.free_group_subgroup
import neat.initial
import data.nat.digits
/-!
# The base case of the `group_thingy` tactic

## Main definitions
The only definition used outside of this file is `base_case_solver`.
`base_case_solver T r₁ r₂` solves the word problem for the relation `of' r₁ r₂`, returning
a normalized word in `T` when possible, and `none` otherwise
-/
variables {ι : Type} [decidable_eq ι]

open multiplicative free_group P semidirect_product

@[simp] lemma gpowers_hom_apply {G : Type*} [group G] (x : G) (y : C∞) :
  gpowers_hom G x y = x ^ y.to_add := rfl

def base_case'_cons (r₁ : ι) (r₂ : C∞) (i : ι) (n : C∞) :
  P (free_group ι) → P (free_group ι)
| ⟨w, ⟨[], _⟩⟩ :=
  if i = r₁ ∧ to_add r₂ ∣ to_add n
  then ⟨of' (1 : free_group ι) (of_add (to_add n / to_add r₂)) * w, 1⟩
  else ⟨mul_free (of' i n) w, ⟨[⟨i, n⟩], sorry⟩⟩
| ⟨w, ⟨(j::l), h⟩⟩ :=
  if i = r₁
  then let x := to_add n + to_add j.2 in
    if j.1 = r₁ ∧ to_add r₂ ∣ x
    then ⟨mul_free (of' i n) w * of' (1 : free_group ι) (of_add (x / (to_add r₂))), ⟨l, sorry⟩⟩
    else if (to_add r₂ : ℤ) ∣ to_add n
      then ⟨mul_free (of' i n) w * of' (1 : free_group ι) (of_add (to_add n / to_add r₂)),
        ⟨(j :: l), h⟩⟩
      else ⟨mul_free (of' i n) w, of' i n * ⟨j :: l, h⟩⟩
  else ⟨mul_free (of' i n) w, of' i n * ⟨j :: l, h⟩⟩

def base_case' (r₁ : ι) (r₂ : C∞) : free_group ι → P (free_group ι)
| ⟨[], h⟩ := ⟨1, ⟨[], h⟩⟩
| ⟨(i::l), h⟩ :=
  base_case'_cons r₁ r₂ i.1 i.2 $ base_case' ⟨l, coprod.pre.reduced_of_reduced_cons h⟩
using_well_founded { rel_tac := λ _ _, `[exact ⟨λ _ _, true, sorry⟩], dec_tac := `[trivial] }

def base_case'_solver (T : set ι) [decidable_pred T] (r₁ : ι) (r₂ : C∞) : solver (of' r₁ r₂) T :=
λ w, let p := base_case' r₁ r₂ w in
if p.right ∈ closure_var T
  then some p
  else none

/-- `base_case_core` takes a word `l₁` in the free_group as a `list (Σ i : ι, C∞)`
and a normalized word with proof `p` as a `P (free_group ι)`.
It returns a normalized version `reverse l₁ * p`, reduced modulo `of' r₁ r₂`  -/
@[inline] def base_case_core (r₁ : ι) (r₂ : C∞) : list (Σ i : ι, C∞) →
  P (free_group ι) → P (free_group ι)
| []     p := p
| (i::l₁)  ⟨p, ⟨[], _⟩⟩ :=
  if i.1 = r₁
    then if to_add r₂ ∣ i.2
      then let q := to_add i.2 / to_add r₂ in
        base_case_core l₁ (inl (of' (1 : free_group ι) q) * ⟨p, 1⟩)
      else base_case_core l₁ (inr (of' i.1 i.2) * ⟨p, 1⟩)
    else base_case_core l₁ (inr (of' i.1 i.2) * inl p)
| (i::l₁) ⟨p, ⟨j::l₂, _⟩⟩ :=
  if i.1 = r₁
    then if j.1 = r₁
      then
        let x := to_add i.2 + to_add j.2 in
        if to_add r₂ ∣ x
        then base_case_core l₁ (inl (of' (1 : free_group ι) (of_add (to_add x / to_add r₂))) *
          inr (of' j.1 j.2⁻¹) * ⟨p, ⟨j::l₂, sorry⟩⟩)
        else base_case_core l₁ (inr (of' i.1 i.2) * ⟨p, ⟨j::l₂, sorry⟩⟩)
      else if to_add r₂ ∣ i.2
        then let q := to_add i.2 / to_add r₂ in
          base_case_core l₁ (inl (of' (1 : free_group ι) q) * ⟨p, ⟨j::l₂, sorry⟩⟩)
        else base_case_core l₁ (inr (of' i.1 i.2) * ⟨p, ⟨j::l₂, sorry⟩⟩)
    else base_case_core l₁ (inr (of' i.1 i.2) * ⟨p, ⟨j::l₂, sorry⟩⟩)

-- def normalize_single (r₁ : ι) (r₂ : C∞) (i : ι) (n : C∞) : P (free_group ι) :=
-- if i = r₁ ∧ to_add r₂ ∣ to_add n
--   then ⟨of' 1 (of_add (to_add n / to_add r₂)), 1⟩
--   else ⟨1, of' i n⟩

-- def mul_left (r₁ : ι) (r₂ : C∞) (i : ι) (n : C∞) :
--   P (free_group ι) → P (free_group ι)
-- | ⟨p, ⟨[], _⟩⟩ := normalize_single r₁ r₂ i n * inl p
-- | ⟨p, ⟨(j::l), _⟩⟩ :=
-- if i = j.1
--   then _
--   else _

-- -- @[inline] def base_case_core₂ (r₁ : ι) (r₂ : C∞) : list (Σ i : ι, C∞) →
-- --   P (free_group ι) → P (free_group ι)
-- -- | []     p := p
-- -- | (i::l₁)  ⟨p, ⟨[], _⟩⟩ :=
-- --   if i.1 = r₁
-- --     then if to_add r₂ ∣ i.2
-- --       then let q := to_add i.2 / to_add r₂ in
-- --         base_case_core l₁ (inl (of' (1 : free_group ι) q) * ⟨p, 1⟩)
-- --       else base_case_core l₁ (inr (of' i.1 i.2) * ⟨p, 1⟩)
-- --     else base_case_core l₁ (inr (of' i.1 i.2) * inl p)
-- -- | (i::l₁) ⟨p, ⟨j::l₂, _⟩⟩ :=
-- --   if i.1 = r₁
-- --     then if j.1 = r₁
-- --       then
-- --         let x := to_add i.2 + to_add j.2 in
-- --         if to_add r₂ ∣ x
-- --         then base_case_core l₁ (inl (of' (1 : free_group ι) (of_add (to_add x / to_add r₂))) *
-- --           inr (of' j.1 j.2⁻¹) * ⟨p, ⟨j::l₂, sorry⟩⟩)
-- --         else base_case_core l₁ (inr (of' i.1 i.2) * ⟨p, ⟨j::l₂, sorry⟩⟩)
-- --       else if to_add r₂ ∣ i.2
-- --         then let q := to_add i.2 / to_add r₂ in
-- --           base_case_core l₁ (inl (of' (1 : free_group ι) q) * ⟨p, ⟨j::l₂, sorry⟩⟩)
-- --         else base_case_core l₁ (inr (of' i.1 i.2) * ⟨p, ⟨j::l₂, sorry⟩⟩)
-- --     else base_case_core l₁ (inr (of' i.1 i.2) * ⟨p, ⟨j::l₂, sorry⟩⟩)

/-- `base_case` reduces a word `w` in the `free_group ι` modulo `of' r₁ r₂` -/
@[inline] def base_case (r₁ : ι) (r₂ : C∞) (w : free_group ι) : P (free_group ι) :=
base_case_core r₁ r₂ w.to_list.reverse 1

/-- `base_case_solver T r₁ r₂` solves the word problem for the relation `of' r₁ r₂`, returning
a normalized word in `T` when possible, and `none` otherwise -/
@[inline] def base_case_solver (T : set ι) [decidable_pred T] (r₁ : ι) (r₂ : C∞) : solver (of' r₁ r₂) T :=
λ w, let p := base_case r₁ r₂ w in
if p.right ∈ closure_var T
  then some p
  else none

#eval --(of' 0 (of_add 2))
  P.lhs (of' 0 (of_add 2)) ((base_case 0 (of_add 2) ((of 1)⁻¹ *of 0^(-2 : ℤ) * (of 1)⁻¹ * of 0 ^2* (of 1)^(-2 : ℤ) * (of 0)^2)))
#eval ((base_case 1 (of_add 1) ((of 0)⁻¹ * of 1 * of 0 ^ 2 * (of 1) * (of 0)⁻¹)).left)
#eval ((base_case' 0 (of_add 2) (of 1 *of 0^2 * (of 1) * of 0 ^2* (of 1)^(-2 : ℤ) * (of 0)^2)).left)
#eval ((base_case' 1 (of_add 1) ((of 0)⁻¹ * of 1 * of 0 ^ 2 * (of 1) * (of 0)⁻¹)).left)

@[simp] lemma lhs_base_case'_cons (r₁ : ι) (r₂ : C∞) (hr₂ : to_add r₂ ≠ 0) (i : ι) (n : C∞) :
  Π (x : P (free_group ι)), lhs (of' r₁ r₂) (base_case'_cons r₁ r₂ i n x) =
    of' i n * lhs (of' r₁ r₂) x
| ⟨w, ⟨[], _⟩⟩ := begin
  rw [base_case'_cons],
  split_ifs,
  { clear_aux_decl,
    rcases h with ⟨rfl, m, hm⟩,
    simp [lhs_inl, free_group.lift, gpowers_hom_apply],
    simp only [of'_eq_of_pow, ← gpow_add, ← gpow_neg, ← gpow_mul,
      int.div_eq_of_eq_mul_right hr₂ hm],
    rw hm },
  { simp [inl_aut] }
end
| ⟨w, ⟨(j::l), _⟩⟩ := begin
  clear_aux_decl,
  rw [base_case'_cons],
  dsimp only,
  split_ifs,
  { subst r₁,
    rcases h_1 with ⟨rfl, m, hm⟩,
    rw [int.div_eq_of_eq_mul_right hr₂ hm],
    rw [← eq_sub_iff_add_eq] at hm,
    simp [lhs_inl, free_group.lift, mul_assoc, gpowers_hom_apply, inl_aut, hm],
    simp only [of'_eq_of_pow, ← gpow_add, ← gpow_neg, ← gpow_mul, ← mul_assoc, hm],
    simp },
  { subst r₁,
    rcases h_2 with ⟨m, hm⟩,
    rw [int.div_eq_of_eq_mul_right hr₂ hm],
    simp [lhs_inl, free_group.lift, mul_assoc, gpowers_hom_apply, inl_aut, hm],
    simp only [of'_eq_of_pow, ← gpow_add, ← gpow_neg, ← gpow_mul, ← mul_assoc, hm],
    simp },
  { simp [inl_aut_inv, inl_aut, mul_assoc] },
  { simp [inl_aut_inv, inl_aut, mul_assoc] }
end

lemma lhs_base_case' (r₁ : ι) (r₂ : C∞) (hr₂ : to_add r₂ ≠ 0) :
  ∀ x : free_group ι, lhs (of' r₁ r₂) (base_case' r₁ r₂ x) = x
| ⟨[], h⟩     := by rw [base_case']; simp
| ⟨(i::l), _⟩ := by rw [base_case', lhs_base_case'_cons, lhs_base_case'];
    simp [inl_aut, inl_aut_inv, mul_assoc, hr₂]
using_well_founded { rel_tac := λ _ _, `[exact ⟨λ _ _, true, sorry⟩], dec_tac := `[trivial] }