/-
Long exact sequence of the exponential sequence of sheaves, round 5:
the sheaf long exact sequence with c1, for the actual exponential
sequence 0 -> Z -> O_X -> O_X^* -> 0 on a complex manifold.

STATUS: This file compiles under Lean 4 with mathlib. Every theorem in
it is checked by the Lean kernel with no `sorry`.

What is proved here, and what is not:

* PROVED: the exponential sequence as a short exact sequence of
  sheaves of abelian groups on a complex manifold. The three sheaves
  are built as `TopCat.Sheaf AddCommGrp` on the opens site:
  `locallyConstantIntSheafAdd` (Z, the sheaf of locally constant
  integer-valued functions), `holomorphicSheafAddCommGrp` (O_X, from
  the commutative ring sheaf of round 3), and
  `holomorphicSheafUnitsAddCommGrp` (O_X^*, the nowhere zero
  holomorphic functions with pointwise multiplication written
  additively). The inclusion `expSeqIncl : Z -> O_X` sends a locally
  constant integer n to 2 pi i n, and `expSeqExp : O_X -> O_X^*` is
  the exponential map. They form the short complex
  `expSeqShortComplex`, and it is short exact
  (`expSeq_shortExact`): the inclusion is a monomorphism, exp is an
  epimorphism, and the inclusion is the kernel of exp.
* PROVED: the two analytic inputs to that exactness, at the level of
  sections. Exactness at O_X is `intOfExpEqOne_isLocallyConstant`:
  a holomorphic section f with exp f = 1 is locally constant with
  values in 2 pi i Z, proved from continuity of f and discreteness
  of Z (no logarithm needed). Surjectivity of exp is
  `expSeqExp_isLocallySurjective`: every nowhere zero holomorphic
  section has a holomorphic logarithm locally, proved from the
  principal branch of log on a disk in the right half-plane
  (`Complex.differentiableAt_log` on the slit plane).
* PROVED: the long exact sequence fragment with c1 identified.
  `expSeq_chernClass` is the connecting homomorphism
  `H^1(X, O_X^*) ->+ H^2(X, Z)` for the actual exponential sequence,
  exact at both joints (`expSeq_chernClass_exact_left`,
  `expSeq_chernClass_exact_right`), surjecting onto the kernel of
  `H^2(Z) -> H^2(O_X)` (`expSeq_chernClass_surj_onto_kernel`), by
  instantiating the abstract construction of `Hodge.ChernClass` with
  the short exact sequence proved here. The Lefschetz (1,1) bridge
  `lefschetz_one_one_of_expSeq` is the round 4 bridge theorem with
  the abstract sequence replaced by the exponential sequence: every
  Hodge class of type (1,1) is algebraic, conditional only on the
  Dolbeault isomorphism and the Hodge decomposition.
* PROVED as a byproduct: in any abelian category, a monomorphism
  that is also an epimorphism is an isomorphism
  (`isIso_of_mono_of_epi_of_abelian`), hence every abelian category
  is balanced (`balanced_of_abelian`). Mathlib v4.13.0 does not
  provide this instance; it is proved here from
  `Abelian.monoIsKernelOfCokernel` and the fact that the cokernel
  of an epimorphism is zero.
* NOT PROVED, still blocked: the Dolbeault isomorphism itself,
  `H^q(X, O_X) ≃ H^{0,q}(X)`, and the Hodge decomposition. Mathlib
  v4.13.0 has no differential forms on manifolds, so the Dolbeault
  cohomology groups cannot be stated; the full (1,1) theorem stays
  conditional on exactly those two inputs, now with the sheaf long
  exact sequence proved instead of assumed. Nothing here claims the
  Hodge conjecture, or any Millennium problem, is solved.
-/

import Hodge.SheafOX
import Hodge.ChernClass
import Mathlib.CategoryTheory.Sites.EpiMono
import Mathlib.CategoryTheory.Sites.LocallySurjective
import Mathlib.CategoryTheory.Sites.Abelian
import Mathlib.Topology.Sheaves.LocallySurjective
import Mathlib.Topology.LocallyConstant.Basic
import Mathlib.CategoryTheory.Abelian.Basic
import Mathlib.Analysis.SpecialFunctions.Complex.Log
import Mathlib.Analysis.SpecialFunctions.Complex.LogDeriv

open scoped Manifold Topology
open CategoryTheory CategoryTheory.Limits TopologicalSpace Opposite

namespace Hodge

variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℂ E]
  {H : Type*} [TopologicalSpace H] (I : ModelWithCorners ℂ E H)
  (M : Type) [TopologicalSpace M] [ChartedSpace H M]

/-! ### Balanced abelian categories -/

/-- In an abelian category, a monomorphism that is also an epimorphism
is an isomorphism. The cokernel of an epimorphism is zero, and a
monomorphism is the kernel of its cokernel, so the map is the kernel
of the zero morphism, hence an isomorphism. -/
theorem isIso_of_mono_of_epi_of_abelian {C : Type*} [Category C] [Abelian C]
    {X Y : C} (f : X ⟶ Y) [Mono f] [Epi f] : IsIso f := by
  have hπ : cokernel.π f = 0 := (cancel_epi f).mp (by rw [cokernel.condition, comp_zero])
  have hcolim : IsColimit (CokernelCofork.ofπ (0 : Y ⟶ cokernel f) (by simp)) :=
    IsColimit.ofIsoColimit (cokernelIsCokernel f) (ofπCongr (w := cokernel.condition f) hπ)
  have hlim := CategoryTheory.Abelian.monoIsKernelOfCokernel
    (CokernelCofork.ofπ (0 : Y ⟶ cokernel f) (by simp)) hcolim
  exact KernelFork.IsLimit.isIso_ι _ hlim rfl

/-- Every abelian category is balanced. -/
instance balanced_of_abelian {C : Type*} [Category C] [Abelian C] : Balanced C where
  isIso_of_mono_of_epi f := isIso_of_mono_of_epi_of_abelian f

/-! ### The sheaf Z of locally constant integer functions -/

/-- The local predicate "is locally constant", for integer-valued
functions on a complex manifold. Restriction preserves local
constancy because the inclusion of an open set is continuous, and
local constancy is local because the inclusion is an open embedding,
so neighborhoods push forward along it. -/
noncomputable def locallyConstantIntLocalPredicate :
    TopCat.LocalPredicate (fun _ : TopCat.of M => ℤ) where
  pred {U} f := IsLocallyConstant f
  res {U V} i f hf :=
    hf.comp_continuous (Opens.isOpenEmbedding_of_le i.le).continuous
  locality {U} f hf := by
    show IsLocallyConstant f
    rw [IsLocallyConstant.iff_eventually_eq]
    intro x
    obtain ⟨V, hxV, i, hi⟩ := hf x
    have hev := (IsLocallyConstant.iff_eventually_eq _).mp hi ⟨x, hxV⟩
    have hix : (i ⟨x, hxV⟩ : ↥U) = x := Subtype.ext rfl
    rw [hix] at hev
    have hmap : Filter.map (Set.inclusion i.le) (𝓝 ⟨x, hxV⟩) = 𝓝 x := by
      rw [IsOpenEmbedding.map_nhds_eq (Opens.isOpenEmbedding_of_le i.le) ⟨x, hxV⟩]
      exact congrArg _ (Subtype.ext rfl)
    rw [← hmap, Filter.eventually_map]
    exact hev

/-- The sheaf Z of locally constant integer-valued functions on M, as
a sheaf of types. -/
noncomputable def locallyConstantIntSheaf : TopCat.Sheaf (Type 0) (TopCat.of M) :=
  TopCat.subsheafToTypes (locallyConstantIntLocalPredicate M)

/-- The additive subgroup of locally constant integer-valued functions
on an open subset of M. -/
noncomputable def locallyConstantIntAddSubgroup (U : Opens M) : AddSubgroup (↥U → ℤ) where
  carrier := {f | IsLocallyConstant f}
  add_mem' := fun hf hg => hf.comp₂ hg (· + ·)
  zero_mem' := IsLocallyConstant.const 0
  neg_mem' := fun hf => hf.comp Neg.neg

/-- The pointwise additive group structure on the locally constant
integer-valued functions: sums and negations of locally constant
functions are locally constant. -/
noncomputable instance (U : (Opens (TopCat.of M))ᵒᵖ) :
    AddCommGroup ((locallyConstantIntSheaf M).presheaf.obj U) :=
  inferInstanceAs (AddCommGroup ↥(locallyConstantIntAddSubgroup M (unop U)))

/-- The presheaf of abelian groups of locally constant integer-valued
functions on M. -/
noncomputable def locallyConstantIntPresheafAddCommGrp :
    TopCat.Presheaf AddCommGrp.{0} (TopCat.of M) where
  obj := fun U ↦ AddCommGrp.of ((locallyConstantIntSheaf M).presheaf.obj U)
  map := fun {U V} h ↦ AddCommGrp.ofHom
    { toFun := (locallyConstantIntSheaf M).presheaf.map h
      map_zero' := by
        apply Subtype.ext
        rfl
      map_add' := fun f g ↦ Subtype.ext rfl }
  map_id := fun _ ↦ rfl
  map_comp := fun _ _ ↦ rfl

/-- The sheaf Z of locally constant integer-valued functions on M, as
a sheaf of abelian groups. -/
noncomputable def locallyConstantIntSheafAdd : TopCat.Sheaf AddCommGrp.{0} (TopCat.of M) :=
  { val := locallyConstantIntPresheafAddCommGrp M
    cond := by
      rw [CategoryTheory.Presheaf.isSheaf_iff_isSheaf_forget _ _
        (CategoryTheory.forget AddCommGrp)]
      exact CategoryTheory.Sheaf.cond (locallyConstantIntSheaf M) }

/-! ### O_X as a sheaf of abelian groups -/

/-- The presheaf of abelian groups of holomorphic functions on M: the
additive group underlying the commutative ring structure of round 3. -/
noncomputable def holomorphicPresheafAddCommGrp :
    TopCat.Presheaf AddCommGrp.{0} (TopCat.of M) where
  obj := fun U ↦ AddCommGrp.of ((holomorphicSheaf I M).presheaf.obj U)
  map := fun {U V} h ↦ AddCommGrp.ofHom
    { toFun := (holomorphicSheaf I M).presheaf.map h
      map_zero' := by
        apply Subtype.ext
        rfl
      map_add' := fun f g ↦ Subtype.ext rfl }
  map_id := fun _ ↦ rfl
  map_comp := fun _ _ ↦ rfl

/-- The sheaf O_X of holomorphic functions on M, as a sheaf of abelian
groups. -/
noncomputable def holomorphicSheafAddCommGrp : TopCat.Sheaf AddCommGrp.{0} (TopCat.of M) :=
  { val := holomorphicPresheafAddCommGrp I M
    cond := by
      rw [CategoryTheory.Presheaf.isSheaf_iff_isSheaf_forget _ _
        (CategoryTheory.forget AddCommGrp)]
      exact CategoryTheory.Sheaf.cond (holomorphicSheaf I M) }

/-! ### O_X^* as a sheaf of abelian groups -/

/-- The pointwise additive group structure on the nowhere zero
holomorphic functions, with addition given by pointwise
multiplication: this is the abelian group structure of O_X^*
written additively, so that the exponential map is a group
homomorphism from the additive group O_X. It is the `Additive`
form of the commutative group structure of round 3. -/
noncomputable instance (U : (Opens (TopCat.of M))ᵒᵖ) :
    AddCommGroup ((holomorphicUnitsSheaf I M).presheaf.obj U) :=
  inferInstanceAs (AddCommGroup (Additive ((holomorphicUnitsSheaf I M).presheaf.obj U)))

/-- The presheaf of abelian groups of nowhere zero holomorphic
functions on M, with the additive notation above. -/
noncomputable def holomorphicPresheafUnitsAddCommGrp :
    TopCat.Presheaf AddCommGrp.{0} (TopCat.of M) where
  obj := fun U ↦ AddCommGrp.of ((holomorphicUnitsSheaf I M).presheaf.obj U)
  map := fun {U V} h ↦ AddCommGrp.ofHom
    { toFun := (holomorphicUnitsSheaf I M).presheaf.map h
      map_zero' := by
        apply Subtype.ext
        rfl
      map_add' := fun f g ↦ Subtype.ext rfl }
  map_id := fun _ ↦ rfl
  map_comp := fun _ _ ↦ rfl

/-- The sheaf O_X^* of nowhere zero holomorphic functions on M, as a
sheaf of abelian groups. -/
noncomputable def holomorphicSheafUnitsAddCommGrp :
    TopCat.Sheaf AddCommGrp.{0} (TopCat.of M) :=
  { val := holomorphicPresheafUnitsAddCommGrp I M
    cond := by
      rw [CategoryTheory.Presheaf.isSheaf_iff_isSheaf_forget _ _
        (CategoryTheory.forget AddCommGrp)]
      exact CategoryTheory.Sheaf.cond (holomorphicUnitsSheaf I M) }

/-! ### The exponential sequence as a short complex of sheaves -/

/-- The opens site admits sheafification for abelian groups, so the
category of sheaves of abelian groups on M is abelian and has zero
morphisms. -/
noncomputable instance : HasSheafify (Opens.grothendieckTopology (TopCat.of M)) AddCommGrp.{0} :=
  Hodge.hasSheafify_small_site

/-- The category of sheaves of abelian groups on M is abelian. The
`TopCat.Sheaf` wrapper is a nonreducible definition, so the
`sheafIsAbelian` instance does not fire on it directly by typeclass
search, and the transport is done by hand. -/
noncomputable instance : Abelian (TopCat.Sheaf AddCommGrp.{0} (TopCat.of M)) :=
  inferInstanceAs (Abelian (CategoryTheory.Sheaf
    (Opens.grothendieckTopology (TopCat.of M)) AddCommGrp.{0}))

/-- The category of sheaves of abelian groups on M has Ext groups.
The general `sheaf_hasExt` instance does not fire by typeclass search
at this concrete site (its universe levels are left as metavariables
and the search times out), so the instance is given concretely, with
the `TopCat.Sheaf` head and the universe levels pinned. -/
noncomputable instance : HasExt.{1, 0, 1} (TopCat.Sheaf AddCommGrp.{0} (TopCat.of M)) :=
  Hodge.sheaf_hasExt (C := Opens (TopCat.of M))
    (J := Opens.grothendieckTopology (TopCat.of M))

/-- A locally constant complex-valued function on a complex manifold
is holomorphic: at each point it is eventually equal to a constant
function. -/
theorem mdifferentiable_of_isLocallyConstant {N : Type*} [TopologicalSpace N]
    [ChartedSpace H N] {f : N → ℂ} (hf : IsLocallyConstant f) :
    MDifferentiable I 𝓘(ℂ, ℂ) f := by
  intro x
  have hconst : MDifferentiableAt I 𝓘(ℂ, ℂ) (fun _ : N => f x) x := mdifferentiable_const x
  exact hconst.congr_of_eventuallyEq (hf.eventually_eq x)

/-- The inclusion Z -> O_X, sending a locally constant integer n to
the holomorphic function 2 pi i n. -/
noncomputable def expSeqIncl :
    locallyConstantIntSheafAdd M ⟶ holomorphicSheafAddCommGrp I M :=
  CategoryTheory.Sheaf.Hom.mk
    { app := fun U ↦ AddCommGrp.ofHom
        { toFun := fun n ↦ ⟨fun x => (n.1 x : ℂ) * (2 * Real.pi * Complex.I),
            mdifferentiable_of_isLocallyConstant I
              (n.2.comp (fun z : ℤ => (z : ℂ) * (2 * Real.pi * Complex.I)))⟩
          map_zero' := by
            apply Subtype.ext
            funext x
            dsimp only
            have h1 : Subtype.val (0 : (locallyConstantIntSheaf M).presheaf.obj U) = 0 := rfl
            have h2 : ((0 : (holomorphicSheaf I M).presheaf.obj U) : ↥(unop U) → ℂ)
                = 0 := rfl
            rw [h1, h2]
            simp
          map_add' := fun n m ↦ by
            apply Subtype.ext
            funext x
            dsimp only
            have h1 : Subtype.val (n + m : (locallyConstantIntSheaf M).presheaf.obj U)
                = Subtype.val n + Subtype.val m := rfl
            have h2 : ∀ a b : (holomorphicSheaf I M).presheaf.obj U,
                ((a + b : (holomorphicSheaf I M).presheaf.obj U) : ↥(unop U) → ℂ)
                  = (a : ↥(unop U) → ℂ) + (b : ↥(unop U) → ℂ) := fun _ _ => rfl
            rw [h1, h2]
            simp [Int.cast_add, add_mul] }
      naturality := fun {U V} h ↦ by
        apply AddMonoidHom.ext
        intro n
        apply Subtype.ext
        funext x
        rfl }

/-- The exponential map O_X -> O_X^* as a morphism of sheaves of
abelian groups: exp(f + g) = exp f * exp g, written additively on
the target. -/
noncomputable def expSeqExp :
    holomorphicSheafAddCommGrp I M ⟶ holomorphicSheafUnitsAddCommGrp I M :=
  CategoryTheory.Sheaf.Hom.mk
    { app := fun U ↦ AddCommGrp.ofHom
        { toFun := fun f ↦ ⟨Complex.exp ∘ f.1,
            ⟨holomorphic_exp I M ⟨f.1, f.2⟩, fun x => Complex.exp_ne_zero _⟩⟩
          map_zero' := by
            apply Subtype.ext
            funext x
            dsimp only
            have h1 : ((0 : (holomorphicSheaf I M).presheaf.obj U) : ↥(unop U) → ℂ)
                = 0 := rfl
            have h2 : Subtype.val (0 : (holomorphicUnitsSheaf I M).presheaf.obj U) = 1 := rfl
            rw [h1, h2]
            simp
          map_add' := fun f g ↦ by
            apply Subtype.ext
            funext x
            dsimp only
            have h1 : ∀ a b : (holomorphicSheaf I M).presheaf.obj U,
                ((a + b : (holomorphicSheaf I M).presheaf.obj U) : ↥(unop U) → ℂ)
                  = (a : ↥(unop U) → ℂ) + (b : ↥(unop U) → ℂ) := fun _ _ => rfl
            have h2 : ∀ a b : (holomorphicUnitsSheaf I M).presheaf.obj U,
                Subtype.val (a + b : (holomorphicUnitsSheaf I M).presheaf.obj U)
                  = Subtype.val a * Subtype.val b := fun _ _ => rfl
            rw [h1, h2]
            simp [Complex.exp_add] }
      naturality := fun {U V} h ↦ by
        apply AddMonoidHom.ext
        intro f
        apply Subtype.ext
        funext x
        rfl }

/-- The exponential sequence 0 -> Z -> O_X -> O_X^* -> 0 as a short
complex of sheaves of abelian groups: exp of 2 pi i n is 1. -/
noncomputable def expSeqShortComplex :
    ShortComplex (TopCat.Sheaf AddCommGrp.{0} (TopCat.of M)) where
  X₁ := locallyConstantIntSheafAdd M
  X₂ := holomorphicSheafAddCommGrp I M
  X₃ := holomorphicSheafUnitsAddCommGrp I M
  f := expSeqIncl I M
  g := expSeqExp I M
  zero := by
    apply CategoryTheory.Sheaf.Hom.ext
    apply CategoryTheory.NatTrans.ext
    funext U
    apply AddMonoidHom.ext
    intro n
    apply Subtype.ext
    funext x
    show Complex.exp ((n.1 x : ℂ) * (2 * Real.pi * Complex.I)) = 1
    exact Complex.exp_int_mul_two_pi_mul_I _

/-! ### Exactness at O_X: the integer of a section in the kernel of exp -/

/-- The pointwise integer of a holomorphic section in the kernel of
exp: at each point, `f x = n x * 2 pi i`, chosen from
`Complex.exp_eq_one_iff`. -/
noncomputable def intOfExpEqOne {U : (Opens (TopCat.of M))ᵒᵖ}
    (f : (holomorphicSheaf I M).presheaf.obj U)
    (hf1 : ∀ x : ↥(unop U), Complex.exp ((f : ↥(unop U) → ℂ) x) = 1) :
    ↥(unop U) → ℤ :=
  fun x => Classical.choose ((Complex.exp_eq_one_iff).mp (hf1 x))

/-- The defining property of the pointwise integer. -/
theorem intOfExpEqOne_spec {U : (Opens (TopCat.of M))ᵒᵖ}
    (f : (holomorphicSheaf I M).presheaf.obj U)
    (hf1 : ∀ x : ↥(unop U), Complex.exp ((f : ↥(unop U) → ℂ) x) = 1) (x : ↥(unop U)) :
    (f : ↥(unop U) → ℂ) x
      = (intOfExpEqOne I M f hf1 x : ℂ) * (2 * Real.pi * Complex.I) :=
  Classical.choose_spec ((Complex.exp_eq_one_iff).mp (hf1 x))

/-- The pointwise integer of a holomorphic section in the kernel of
exp is locally constant: continuity of `f` and discreteness of `ℤ`
force the integer to be constant near each point, since two values
of `f` closer than `pi` cannot differ by a nonzero multiple of
`2 pi i`. -/
theorem intOfExpEqOne_isLocallyConstant {U : (Opens (TopCat.of M))ᵒᵖ}
    (f : (holomorphicSheaf I M).presheaf.obj U)
    (hf1 : ∀ x : ↥(unop U), Complex.exp ((f : ↥(unop U) → ℂ) x) = 1) :
    IsLocallyConstant (intOfExpEqOne I M f hf1) := by
  rw [IsLocallyConstant.iff_eventually_eq]
  intro x₀
  have hcont : ContinuousAt (f : ↥(unop U) → ℂ) x₀ :=
    (holomorphicSheaf.isHolomorphic I M f).continuous.continuousAt
  have hball : ∀ᶠ y in 𝓝 x₀,
      ‖(f : ↥(unop U) → ℂ) y - (f : ↥(unop U) → ℂ) x₀‖ < Real.pi := by
    have hnorm : ContinuousAt
        (fun y => ‖(f : ↥(unop U) → ℂ) y - (f : ↥(unop U) → ℂ) x₀‖) x₀ :=
      (hcont.sub continuousAt_const).norm
    have h0 : ‖(f : ↥(unop U) → ℂ) x₀ - (f : ↥(unop U) → ℂ) x₀‖ < Real.pi := by
      rw [sub_self, norm_zero]
      exact Real.pi_pos
    exact hnorm.eventually (Iio_mem_nhds h0)
  filter_upwards [hball] with y hy
  have hdiff : ((intOfExpEqOne I M f hf1 y - intOfExpEqOne I M f hf1 x₀ : ℤ) : ℂ)
        * (2 * Real.pi * Complex.I)
      = (f : ↥(unop U) → ℂ) y - (f : ↥(unop U) → ℂ) x₀ := by
    have h1 := intOfExpEqOne_spec I M f hf1 y
    have h2 := intOfExpEqOne_spec I M f hf1 x₀
    rw [h1, h2]
    push_cast
    ring
  have hnorm : ‖((intOfExpEqOne I M f hf1 y - intOfExpEqOne I M f hf1 x₀ : ℤ) : ℂ)‖
        * (2 * Real.pi)
      = ‖(f : ↥(unop U) → ℂ) y - (f : ↥(unop U) → ℂ) x₀‖ := by
    have hI : ‖(2 * Real.pi * Complex.I : ℂ)‖ = 2 * Real.pi := by
      rw [norm_mul, norm_mul, Complex.norm_I, mul_one, Complex.norm_real,
        Real.norm_eq_abs, abs_of_nonneg Real.pi_pos.le]
      norm_num
    rw [← hdiff, norm_mul, hI]
  have hlt : |((intOfExpEqOne I M f hf1 y - intOfExpEqOne I M f hf1 x₀ : ℤ) : ℝ)|
      < (1:ℝ)/2 := by
    have hpos : (0:ℝ) < 2 * Real.pi := by positivity
    have h1 : |((intOfExpEqOne I M f hf1 y - intOfExpEqOne I M f hf1 x₀ : ℤ) : ℝ)|
        * (2 * Real.pi) < Real.pi := by
      rw [← Complex.norm_intCast, hnorm]
      exact hy
    have heq : (1:ℝ)/2 = Real.pi / (2 * Real.pi) := by
      field_simp
    rw [heq, lt_div_iff₀ hpos]
    exact h1
  have hd0 : intOfExpEqOne I M f hf1 y - intOfExpEqOne I M f hf1 x₀ = 0 := by
    by_contra hne
    have h1 : (1:ℝ)
        ≤ |((intOfExpEqOne I M f hf1 y - intOfExpEqOne I M f hf1 x₀ : ℤ) : ℝ)| := by
      have h := Int.one_le_abs hne
      exact_mod_cast h
    linarith
  exact sub_eq_zero.mp hd0

/-! ### Exactness at O_X^*: local holomorphic logarithms -/

/-- Every nowhere zero holomorphic section has a holomorphic logarithm
locally: near any point `x₀`, there is an open neighborhood `V` and a
holomorphic function `h` on `V` with `exp (h y) = g y`. The logarithm
is the principal branch of `log` applied to `c * g`, where
`c = ‖g x₀‖ / g x₀` rotates `g x₀` onto the positive real axis, so
that `c * g` stays in the slit plane on a small ball around `x₀`. -/
theorem exists_local_log {U : Opens M} (g : (holomorphicUnitsSheaf I M).presheaf.obj (op U))
    (x₀ : M) (hx₀ : x₀ ∈ U) :
    ∃ V : Opens M, ∃ _ : x₀ ∈ V, ∃ hVU : V ≤ U,
      ∃ h : (holomorphicSheaf I M).presheaf.obj (op V),
        ∀ y : ↥V, Complex.exp ((h : ↥V → ℂ) y)
          = g.1 ⟨y.1, hVU y.2⟩ := by
  set a : ℂ := g.1 ⟨x₀, hx₀⟩
  have ha : a ≠ 0 := g.2.2 ⟨x₀, hx₀⟩
  have hapos : (0:ℝ) < ‖a‖ := norm_pos_iff.mpr ha
  set c : ℂ := (‖a‖ : ℂ) / a with hc_def
  have hc_ne : c ≠ 0 := by
    rw [hc_def]
    exact div_ne_zero (by exact_mod_cast hapos.ne') ha
  have hc_mul : c * a = ‖a‖ := by
    rw [hc_def]
    exact div_mul_cancel₀ _ ha
  -- the ambient log function on U, holomorphic where c * g lands in the slit plane
  have hk_at : ∀ z : ↥U, c * g.1 z ∈ Complex.slitPlane →
      MDifferentiableAt I 𝓘(ℂ, ℂ)
        (fun w => Complex.log (c * g.1 w) - Complex.log c) z := by
    intro z hz
    have hcg : MDifferentiableAt I 𝓘(ℂ, ℂ) (fun w => c * g.1 w) z := by
      have hg : MDifferentiableAt I 𝓘(ℂ, ℂ) g.1 z :=
        holomorphicUnits_isHolomorphic I M g z
      have hconst : MDifferentiableAt I 𝓘(ℂ, ℂ) (fun _ : ↥U => c) z :=
        mdifferentiableAt_const
      exact hconst.mul hg
    have hlog : MDifferentiableAt 𝓘(ℂ, ℂ) 𝓘(ℂ, ℂ) Complex.log (c * g.1 z) :=
      (Complex.differentiableAt_log hz).mdifferentiableAt
    have hcomp : MDifferentiableAt I 𝓘(ℂ, ℂ)
        (Complex.log ∘ fun w => c * g.1 w) z :=
      MDifferentiableAt.comp (f := fun w => c * g.1 w) (g := Complex.log) z hlog hcg
    exact hcomp.sub mdifferentiableAt_const
  have hcont : Continuous (fun z : ↥U => c * g.1 z) :=
    continuous_const.mul (holomorphicUnits_isHolomorphic I M g).continuous
  -- V: the points of U where c * g is within ‖a‖/2 of ‖a‖
  set V : Opens M := ⟨Subtype.val '' ((fun z : ↥U => c * g.1 z) ⁻¹'
      Metric.ball (‖a‖ : ℂ) (‖a‖ / 2)),
    (Opens.isOpenEmbedding' U).isOpenMap _ (Metric.isOpen_ball.preimage hcont)⟩
  have hx₀V : x₀ ∈ V := by
    show x₀ ∈ Subtype.val '' ((fun z : ↥U => c * g.1 z) ⁻¹'
      Metric.ball (‖a‖ : ℂ) (‖a‖ / 2))
    exact ⟨⟨x₀, hx₀⟩, by
      show c * g.1 ⟨x₀, hx₀⟩ ∈ Metric.ball (‖a‖ : ℂ) (‖a‖ / 2)
      rw [show c * g.1 ⟨x₀, hx₀⟩ = (‖a‖ : ℂ) from hc_mul,
        Metric.mem_ball, dist_self]
      exact half_pos hapos, rfl⟩
  have hVU : V ≤ U := by
    intro x hx
    obtain ⟨z, -, rfl⟩ := hx
    exact z.2
  -- c * g lands in the slit plane on V
  have hmem : ∀ y₀ : ↥V, c * g.1 ⟨y₀.1, hVU y₀.2⟩ ∈ Complex.slitPlane := by
    intro y₀
    obtain ⟨z, hz, hzz⟩ := y₀.2
    have hzeq : z = ⟨y₀.1, hVU y₀.2⟩ := Subtype.ext hzz
    rw [hzeq] at hz
    simp only [Set.mem_preimage] at hz
    rw [Metric.mem_ball, dist_eq_norm] at hz
    have hre : (0:ℝ) < (c * g.1 ⟨y₀.1, hVU y₀.2⟩).re := by
      have hle : |(c * g.1 ⟨y₀.1, hVU y₀.2⟩).re - ‖a‖|
          ≤ ‖c * g.1 ⟨y₀.1, hVU y₀.2⟩ - (‖a‖ : ℂ)‖ := by
        have h := Complex.abs_re_le_abs
          (c * g.1 ⟨y₀.1, hVU y₀.2⟩ - (‖a‖ : ℂ))
        rwa [Complex.sub_re, Complex.ofReal_re, Complex.norm_eq_abs] at h
      have hlt := lt_of_le_of_lt hle hz
      rw [abs_lt] at hlt
      linarith
    exact Or.inl hre
  refine ⟨V, hx₀V, hVU, ⟨(fun w => Complex.log (c * g.1 w) - Complex.log c)
      ∘ (Opens.inclusion hVU), ?_⟩, ?_⟩
  · intro y₀
    exact MDifferentiableAt.comp (f := Opens.inclusion hVU)
      (g := fun w => Complex.log (c * g.1 w) - Complex.log c) y₀
      (hk_at ⟨y₀.1, hVU y₀.2⟩ (hmem y₀))
      ((contMDiff_inclusion (n := ⊤) hVU).mdifferentiable le_top y₀)
  · intro y
    show Complex.exp (Complex.log (c * g.1 ⟨y.1, hVU y.2⟩) - Complex.log c)
        = g.1 ⟨y.1, hVU y.2⟩
    rw [Complex.exp_sub, Complex.exp_log (mul_ne_zero hc_ne (g.2.2 _)),
      Complex.exp_log hc_ne, mul_div_cancel_left₀ _ hc_ne]

/-! ### The exponential sequence is short exact -/

/-- The underlying holomorphic function of a section of O_X viewed as
an abelian-group sheaf: the carriers are definitionally the same, so
this is the identity, factored out so that the coercion to a function
resolves. -/
def toHolomorphicSection {U : (Opens (TopCat.of M))ᵒᵖ}
    (s : (holomorphicSheafAddCommGrp I M).val.obj U) :
    (holomorphicSheaf I M).presheaf.obj U := s

/-- Uniqueness of the pointwise integer: if `f x = n * 2 pi i` then the
chosen integer at `x` is `n`. -/
theorem intOfExpEqOne_eq {U : (Opens (TopCat.of M))ᵒᵖ}
    (f : (holomorphicSheaf I M).presheaf.obj U)
    (hf1 : ∀ x : ↥(unop U), Complex.exp ((f : ↥(unop U) → ℂ) x) = 1)
    (x : ↥(unop U)) (n : ℤ)
    (hn : (f : ↥(unop U) → ℂ) x = (n : ℂ) * (2 * Real.pi * Complex.I)) :
    intOfExpEqOne I M f hf1 x = n := by
  have h := intOfExpEqOne_spec I M f hf1 x
  rw [hn] at h
  have h2 : (intOfExpEqOne I M f hf1 x : ℂ) = (n : ℂ) :=
    mul_right_cancel₀ twoPiI_ne_zero h.symm
  exact_mod_cast h2

/-- The inclusion `Z -> O_X` is a monomorphism: it is injective on
sections, since `2 pi i` is nonzero. -/
theorem expSeqIncl_mono : Mono (expSeqIncl I M) := by
  apply CategoryTheory.Sheaf.mono_of_injective
  intro U n m h
  apply Subtype.ext
  funext x
  have hcongr : (n.1 x : ℂ) * (2 * Real.pi * Complex.I)
      = (m.1 x : ℂ) * (2 * Real.pi * Complex.I) :=
    congrFun (congrArg Subtype.val h) x
  have h2 : (n.1 x : ℂ) = (m.1 x : ℂ) := mul_right_cancel₀ twoPiI_ne_zero hcongr
  exact_mod_cast h2

/-- The pointwise kernel fact: if `k ≫ exp = 0`, then `exp` of every
value of `k s` is `1`. -/
theorem expSeqKernel_exp_eq_one {A : TopCat.Sheaf AddCommGrp.{0} (TopCat.of M)}
    (k : A ⟶ holomorphicSheafAddCommGrp I M) (hk : k ≫ expSeqExp I M = 0)
    (U : (Opens (TopCat.of M))ᵒᵖ) (s : A.val.obj U) (x : ↥(unop U)) :
    Complex.exp ((toHolomorphicSection I M (k.val.app U s) : ↥(unop U) → ℂ) x) = 1 := by
  have happ : (expSeqExp I M).val.app U (k.val.app U s) = 0 := by
    have h := DFunLike.congr_fun
      (congrArg (fun φ : A ⟶ holomorphicSheafUnitsAddCommGrp I M => φ.val.app U) hk) s
    exact h
  have hval := congrFun (congrArg Subtype.val happ) x
  exact hval

/-- The lift of a map into `O_X` killed by `exp` to a map into `Z`:
at each open set, a section `s` of `A` maps to the locally constant
integer section determined pointwise by `k s`, using
`intOfExpEqOne`. -/
noncomputable def expSeqKernelLift {A : TopCat.Sheaf AddCommGrp.{0} (TopCat.of M)}
    (k : A ⟶ holomorphicSheafAddCommGrp I M) (hk : k ≫ expSeqExp I M = 0) :
    A ⟶ locallyConstantIntSheafAdd M := by
  have hk1 : ∀ (U : (Opens (TopCat.of M))ᵒᵖ) (s : A.val.obj U) (x : ↥(unop U)),
      Complex.exp ((toHolomorphicSection I M (k.val.app U s) : ↥(unop U) → ℂ) x) = 1 :=
    expSeqKernel_exp_eq_one I M k hk
  refine CategoryTheory.Sheaf.Hom.mk
    { app := fun U ↦ AddCommGrp.ofHom
        { toFun := fun s ↦ ⟨intOfExpEqOne I M (toHolomorphicSection I M (k.val.app U s))
            (hk1 U s),
            intOfExpEqOne_isLocallyConstant I M (toHolomorphicSection I M (k.val.app U s))
              (hk1 U s)⟩
          map_zero' := ?_
          map_add' := ?_ }
      naturality := ?_ }
  · apply Subtype.ext
    funext x
    exact intOfExpEqOne_eq I M (toHolomorphicSection I M (k.val.app U 0)) (hk1 U 0) x 0 (by
      have h0 : k.val.app U (0 : A.val.obj U)
          = (0 : (holomorphicSheafAddCommGrp I M).val.obj U) := map_zero _
      rw [h0]
      show (0:ℂ) = ((0:ℤ):ℂ) * (2 * Real.pi * Complex.I)
      simp)
  · intro s t
    apply Subtype.ext
    funext x
    exact intOfExpEqOne_eq I M (toHolomorphicSection I M (k.val.app U (s + t)))
      (hk1 U (s + t)) x
      (intOfExpEqOne I M (toHolomorphicSection I M (k.val.app U s)) (hk1 U s) x +
        intOfExpEqOne I M (toHolomorphicSection I M (k.val.app U t)) (hk1 U t) x) (by
      have hadd : k.val.app U (s + t) = k.val.app U s + k.val.app U t := map_add _ _ _
      have h1 := intOfExpEqOne_spec I M (toHolomorphicSection I M (k.val.app U s))
        (hk1 U s) x
      have h2 := intOfExpEqOne_spec I M (toHolomorphicSection I M (k.val.app U t))
        (hk1 U t) x
      show ((toHolomorphicSection I M (k.val.app U (s + t)) : ↥(unop U) → ℂ) x)
        = ((intOfExpEqOne I M (toHolomorphicSection I M (k.val.app U s)) (hk1 U s) x +
            intOfExpEqOne I M (toHolomorphicSection I M (k.val.app U t)) (hk1 U t) x : ℤ) : ℂ) *
          (2 * Real.pi * Complex.I)
      rw [hadd]
      show ((toHolomorphicSection I M (k.val.app U s) : ↥(unop U) → ℂ) x +
          (toHolomorphicSection I M (k.val.app U t) : ↥(unop U) → ℂ) x)
        = ((intOfExpEqOne I M (toHolomorphicSection I M (k.val.app U s)) (hk1 U s) x +
            intOfExpEqOne I M (toHolomorphicSection I M (k.val.app U t)) (hk1 U t) x : ℤ) : ℂ) *
          (2 * Real.pi * Complex.I)
      rw [h1, h2, Int.cast_add, add_mul])
  · intro U V h
    apply AddMonoidHom.ext
    intro s
    apply Subtype.ext
    funext y
    have hnat : k.val.app V (A.val.map h s)
        = (holomorphicPresheafAddCommGrp I M).map h (k.val.app U s) :=
      DFunLike.congr_fun (k.val.naturality h) s
    have hval : ((toHolomorphicSection I M (k.val.app V (A.val.map h s))) :
          ↥(unop V) → ℂ) y
        = ((toHolomorphicSection I M (k.val.app U s)) : ↥(unop U) → ℂ) (h.unop y) := by
      rw [hnat]
      rfl
    exact intOfExpEqOne_eq I M (toHolomorphicSection I M (k.val.app V (A.val.map h s)))
      (hk1 V (A.val.map h s)) y
      (intOfExpEqOne I M (toHolomorphicSection I M (k.val.app U s)) (hk1 U s) (h.unop y)) (by
      rw [hval]
      exact intOfExpEqOne_spec I M (toHolomorphicSection I M (k.val.app U s))
        (hk1 U s) (h.unop y))

/-- The lift composed with the inclusion is the original map: at each
point, the integer times `2 pi i` is the value of `k s`. -/
theorem expSeqKernelLift_comp {A : TopCat.Sheaf AddCommGrp.{0} (TopCat.of M)}
    (k : A ⟶ holomorphicSheafAddCommGrp I M) (hk : k ≫ expSeqExp I M = 0) :
    expSeqKernelLift I M k hk ≫ expSeqIncl I M = k := by
  apply CategoryTheory.Sheaf.Hom.ext
  apply CategoryTheory.NatTrans.ext
  funext U
  apply AddMonoidHom.ext
  intro s
  apply Subtype.ext
  funext x
  show ((intOfExpEqOne I M (toHolomorphicSection I M (k.val.app U s))
      (expSeqKernel_exp_eq_one I M k hk U s) x : ℂ) * (2 * Real.pi * Complex.I))
    = ((toHolomorphicSection I M (k.val.app U s) : ↥(unop U) → ℂ) x)
  exact (intOfExpEqOne_spec I M (toHolomorphicSection I M (k.val.app U s))
    (expSeqKernel_exp_eq_one I M k hk U s) x).symm

/-- The inclusion is the kernel of `exp`: the kernel fork is a limit.
`IsLimit` is data in mathlib, not a `Prop`, so this is a `def`, not a
theorem. -/
noncomputable def expSeq_kernelForkIsLimit :
    IsLimit (KernelFork.ofι (expSeqShortComplex I M).f (expSeqShortComplex I M).zero) := by
  haveI : Mono (expSeqShortComplex I M).f := expSeqIncl_mono I M
  apply KernelFork.IsLimit.ofι'
  intro A k hk
  exact ⟨expSeqKernelLift I M k hk, expSeqKernelLift_comp I M k hk⟩

/-- The exponential sequence is exact at `O_X`. -/
theorem expSeqShortComplex_exact : (expSeqShortComplex I M).Exact :=
  (expSeqShortComplex I M).exact_of_f_is_kernel (expSeq_kernelForkIsLimit I M)

/-! ### The exponential map is locally surjective, hence an epimorphism -/

/-- The underlying nowhere zero holomorphic function of a section of
O_X^* viewed as an abelian-group sheaf. -/
def toUnitsSection {U : (Opens (TopCat.of M))ᵒᵖ}
    (s : (holomorphicSheafUnitsAddCommGrp I M).val.obj U) :
    (holomorphicUnitsSheaf I M).presheaf.obj U := s

/-- A holomorphic function viewed as a section of O_X as an
abelian-group sheaf. -/
def ofHolomorphicSection {U : (Opens (TopCat.of M))ᵒᵖ}
    (s : (holomorphicSheaf I M).presheaf.obj U) :
    (holomorphicSheafAddCommGrp I M).val.obj U := s

/-- The exponential map of sheaves is locally surjective: every
nowhere zero holomorphic function has a local logarithm, by
`exists_local_log`. -/
theorem expSeqExp_isLocallySurjective :
    CategoryTheory.Sheaf.IsLocallySurjective (expSeqExp I M) := by
  show TopCat.Presheaf.IsLocallySurjective (expSeqExp I M).val
  rw [TopCat.Presheaf.isLocallySurjective_iff]
  intro U t x hx
  obtain ⟨V, hxV, hVU, h, hexp⟩ :=
    exists_local_log I M (toUnitsSection I M t) x hx
  refine ⟨V, homOfLE hVU, ⟨ofHolomorphicSection I M h, ?_⟩, hxV⟩
  apply Subtype.ext
  funext y
  exact hexp y

/-- The exponential map of sheaves is an epimorphism. -/
theorem expSeqExp_epi : Epi (expSeqExp I M) := by
  haveI : CategoryTheory.Sheaf.IsLocallySurjective (expSeqExp I M) :=
    expSeqExp_isLocallySurjective I M
  exact CategoryTheory.Sheaf.epi_of_isLocallySurjective (expSeqExp I M)

/-! ### The exponential sequence is short exact, and c1 is its connecting homomorphism -/

/-- The exponential sequence `0 -> Z -> O_X -> O_X^* -> 0` is short
exact as sheaves of abelian groups. -/
theorem expSeq_shortExact : (expSeqShortComplex I M).ShortExact :=
  ShortComplex.ShortExact.mk' (expSeqShortComplex_exact I M) (expSeqIncl_mono I M)
    (expSeqExp_epi I M)

/-- The first Chern class of the exponential sequence, as the
connecting homomorphism `H^1(X, O_X^*) ->+ H^2(X, Z)`. -/
noncomputable def expSeq_chernClass : Sheaf.H (holomorphicSheafUnitsAddCommGrp I M) 1 →+
    Sheaf.H (locallyConstantIntSheafAdd M) 2 :=
  sheafChernClass (expSeq_shortExact I M)

/-- Exactness at `H^1(X, O_X^*)`: the kernel of `c1` is the image of
the map induced by `exp`. -/
theorem expSeq_chernClass_exact_left :
    Function.Exact
      ((Abelian.Ext.mk₀ (expSeqShortComplex I M).g).postcomp sheafZ (add_zero 1))
      (expSeq_chernClass I M) :=
  sheaf_chernClass_exact_left (expSeq_shortExact I M)

/-- Exactness at `H^2(X, Z)`: the kernel of the map induced by the
inclusion is the image of `c1`. -/
theorem expSeq_chernClass_exact_right :
    Function.Exact (expSeq_chernClass I M)
      ((Abelian.Ext.mk₀ (expSeqShortComplex I M).f).postcomp sheafZ (add_zero 2)) :=
  sheaf_chernClass_exact_right (expSeq_shortExact I M)

/-- `c1` surjects onto the kernel of `H^2(X, Z) -> H^2(X, O_X)`:
every class in `H^2(X, Z)` killed by the map induced by the inclusion
is the Chern class of a class in `H^1(X, O_X^*)`. -/
theorem expSeq_chernClass_surj_onto_kernel
    (x : Sheaf.H (locallyConstantIntSheafAdd M) 2)
    (hx : ((Abelian.Ext.mk₀ (expSeqShortComplex I M).f).postcomp sheafZ (add_zero 2)) x = 0) :
    ∃ y : Sheaf.H (holomorphicSheafUnitsAddCommGrp I M) 1,
      expSeq_chernClass I M y = x :=
  sheaf_chernClass_surj_onto_kernel (expSeq_shortExact I M) x hx

/-- Lefschetz (1,1) for the exponential sequence, modulo the two
analytic inputs: given the Dolbeault isomorphism and the Hodge
decomposition, every Hodge class of type (1,1) is algebraic, and the
Chern class map is the one from the exponential sequence. -/
theorem lefschetz_one_one_of_expSeq
    {W20 W11 W02 : Type*} [AddCommGroup W20] [AddCommGroup W11] [AddCommGroup W02]
    (ι : Sheaf.H (locallyConstantIntSheafAdd M) 2 →+ HodgeCohom2 W20 W11 W02)
    (e : Sheaf.H (holomorphicSheafAddCommGrp I M) 2 ≃+ W02)
    (hι : proj02.comp ι =
      e.toAddMonoidHom.comp
        ((Abelian.Ext.mk₀ (expSeqShortComplex I M).f).postcomp sheafZ (add_zero 2)))
    (α : Sheaf.H (locallyConstantIntSheafAdd M) 2) (hα : IsHodge11 ι α) :
    IsAlgebraic (expSeq_chernClass I M) α :=
  lefschetz_one_one_of_sheaf_exact (expSeq_shortExact I M) ι e hι α hα

end Hodge
