\import Algebra.Group
\import Algebra.Group.Category
\import Algebra.Meta
\import Algebra.Monoid
\import Algebra.Monoid.Category
\import Algebra.Monoid.Sub
\import Algebra.Pointed.Category
\import Algebra.Ring
\import Algebra.Ring.Category
\import Algebra.Ring.RingHom
\import Algebra.Ring.Ideal
\import Algebra.Ring.Localization
\import Algebra.Semiring
\import Arith.Nat
\import Category
\import Category.Functor
\import Category.Limit
\import Category.Slice
\import Category.Topos.Sheaf
\import Category.Topos.Sheaf.Site
\import Data.Array
\import Data.Bool
\import Data.Maybe
\import Equiv
\import Equiv.Fiber
\import Equiv.Path
\import Equiv.Sigma
\import Function.Meta
\import HLevel
\import Logic
\import Logic.Meta
\import Meta
\import Order.Lattice
\import Order.PartialOrder
\import Paths
\import Paths.Meta
\import Relation.Equivalence
\import Set.Category
\import Topology.Locale
\open Monoid
\open CompleteLattice (SJoin)
\open Bounded (bottom)
\open Ideal

\func SpecPres (R : CRing) : FramePres R \cowith
  | conj => *
  | BasicCover => FramePres.Indexing
      {Maybe (\Sigma R R)} {R}
      (\case __ \with {
        | just (a,b) => (Bool, a + b, if __ a b)
        | nothing => (Empty, 0, absurd)
      })
  \where {
    \lemma cover_ideal {R : CRing} {x : R} {J : \Set} {g : J -> R} (c : Cover {SpecPres R} x g) : radical {closure g} x \elim c
      | cover-basic bc => FramePres.indexing-transport _ (later \case \elim __ \with {
        | nothing => inP (1, inP (nil, zro_*-right))
        | just (a,b) => inP (1, inP ((1, true) :: (1, false) :: nil, equation))
      }) bc
      | cover-inj j idp => radical-superset (closure-superset j)
      | cover-trans {I} {f} c h => \case cover_ideal c \with {
        | inP (n, inP (l,p)) => radical_pow $ rewrite (inv p) in bigSum {radical {closure g}} (map (\lam (c,i) => c * f i) l) \lam i => ideal-left (cover_ideal (h (l i).2))
      }
      | cover-proj1 idp j idp => ideal-right (radical-superset (closure-superset j))
      | cover-idemp j p => radical_pow {_} {x} {2} (simplify (rewriteI p (radical-superset {closure g} (closure-superset j))))
      | cover-comm idp j p => rewrite *-comm (rewriteI p (radical-superset (closure-superset j)))
      | cover-ldistr {a} {b} idp {f} c h => \case cover_ideal c \with {
        | inP (n, inP (l : Array, p)) => inP (suc n, inP (map (\lam (c,j) => (pow a n * b * c, j)) l,
          rewrite (CMonoid.pow_*-comm, p, R.BigSum-ldistr) $ R.BigSum-rdistr *> path (\lam i => AddMonoid.BigSum \new Array R l.len \lam j =>
            (equation {usingOnly (h (l j).2)} : (pow a n * ((l j).1 * f (l j).2)) * (a * b) = (pow a n * b * (l j).1) * g (l j).2) i)
        ))
      }

    \lemma ideal_cover {R : CRing} {x : R} {J : \Set} {g : J -> R} (p : radical {closure g} x) : Cover {SpecPres R} x g \elim p
      | inP (n, inP (l,p)) => cover-trans (cover_pow n) \lam _ => rewrite p $ cover-trans cover_bigSum \lam i => Cover.cover-proj2 idp (l i).2 idp

    \lemma cover_ide {R : CRing} {x : R} : Cover1 {SpecPres R} x 1
      => cover-proj1 (inv ide-left) () idp

    \lemma cover_pow {R : CRing} {x : R} (n : Nat) : Cover1 {SpecPres R} x (pow x n) \elim n
      | 0 => cover_ide
      | suc n => Cover.cover-prod (cover_pow n) (cover-inj () idp)

    \lemma cover_bigSum {R : CRing} {l : Array R} : Cover {SpecPres R} (AddMonoid.BigSum l) l \elim l
      | nil => cover-basic (inP (nothing, \new QEquiv absurd (\case __) (\case __) (\case __), idp, \case __))
      | :: a l => cover-trans (cover-basic (FramePres.indexing-make (just (a, AddMonoid.BigSum l)))) \case \elim __ \with {
        | false => cover-trans cover_bigSum (\lam i => cover-inj (suc i) idp)
        | true => cover-inj 0 idp
      }
  }

\func Spec (R : CRing) : Locale
  => PresentedFrame (SpecPres R)

\record RingedLocale (\coerce L : Locale) (R : VSheaf CRingCat L)
  \where {
    \use \coerce fromSheaf {L : Locale} (S : VSheaf CRingCat L) => \new RingedLocale L S

    {-
    \func equality (L L' : RingedLocale) : Equiv {L = L'} {\Sigma (p : L.L = L'.L) (VSheaf.direct_image_locale (Iso.f {Precat.idtoiso p}) L.R = L'.R)}
      => pathEquiv _ $ later \lam {L : RingedLocale} {L' : RingedLocale} => \new Retraction {
        | f => fromPath
        | sec s => toPath s.1 s.2
        | f_sec s => {?}
      }
      \where {
        \func fromPath {L L' : RingedLocale} (p : L = L') : \Sigma (p : L.L = L'.L) (VSheaf.direct_image_locale (Iso.f {Precat.idtoiso p}) L.R = L'.R) \elim p
          | idp => (idp, VSheaf.direct_image_id L'.R)

        \func toPath {L L' : RingedLocale} (p : L.L = L'.L) (q : VSheaf.direct_image_locale (Iso.f {Precat.idtoiso p}) L.R = L'.R) : L = L'
          => ext (p, VSheaf.transport_direct_image_locale p L.R *> q)

        \func from-to {LR : RingedLocale} {L' : Locale} {R' : VSheaf CRingCat L'} (p : LR.L = L') (q : VSheaf.direct_image_locale (Iso.f {Precat.idtoiso p}) LR.R = R') : fromPath (toPath {LR} {\new RingedLocale L' R'} p q) = (p,q) \elim p, q
          | idp, idp => unfold toPath {?}
      }
    -}
    \func equality1 (L L' : RingedLocale) : Equiv {L = L'} {\Sigma (p : L.L = L'.L) (transport (VSheaf CRingCat) p L.R = L'.R)}
      => pathEquiv _ $ later \lam {L : RingedLocale} {L' : RingedLocale} => \new Retraction {
        | f => fromPath
        | sec s => toPath s.1 s.2
        | f_sec s => from-to {L} {L'.L} {L'.R} s.1 s.2
      }
      \where {
        \func fromPath {L L' : RingedLocale} (p : L = L') : \Sigma (p : L.L = L'.L) (transport (VSheaf CRingCat) p L.R = L'.R) \elim p
          | idp => (idp, idp)

        \func toPath {L L' : RingedLocale} (p : L.L = L'.L) (q : transport (VSheaf CRingCat) p L.R = L'.R) : L = L'
          => ext (p, q)

        \func from-to {LR : RingedLocale} {L' : Locale} {R' : VSheaf CRingCat L'} (p : LR.L = L') (q : transport (VSheaf CRingCat) p LR.R = R') : fromPath (toPath {LR} {\new RingedLocale L' R'} p q) = (p,q) \elim p, q
          | idp, idp => idp
      }

    \func equality2 (L L' : RingedLocale) : Equiv {L = L'} {\Sigma (p : L.L = L'.L) (VSheaf.direct_image_locale (Iso.f {Precat.idtoiso p}) L.R = L'.R)}
      => transEquiv (equality1 L L') $ sigma-right \lam p => pathConcatEquiv (VSheaf.transport_direct_image p L.R)

    \func equality3 (L L' : RingedLocale) : Equiv {L = L'} {\Sigma (e : Iso {LocaleCat} {L.L} {L'.L}) (Iso {_} {VSheaf.direct_image_locale e.f L.R} {L'.R})}
      => equality2 L L' `transEquiv` sigma-left univalence `transEquiv` sigma-right (later (\lam e => univalence))
  }

\record RingedLocaleHom (Dom Cod : RingedLocale) (\coerce f : FrameHom Cod Dom) (f# : NatTrans (\suc \lp) Cod.R (VSheaf.direct_image_locale f Dom.R))
  \where {
    \func fromHomEq {L M : Locale} {f g : FrameHom M L} (p : f = g) (a : M) : f a <= g a
      => transport (\lam (h : FrameHom M L) => f a <= h a) p <=-refl

    \lemma ext {L M : RingedLocale} (f g : RingedLocaleHom L M) (p : f.f = g.f) (q : \Pi (a : M) (x : M.R a) -> L.R.F.Func (fromHomEq p a) (g.f# a x) = f.f# a x) : f = g
      => aux f.f# g.f# p q
      \where {
        \lemma aux {L M : RingedLocale} {f g : FrameHom M L} (f# : NatTrans (\suc \lp) M.R (VSheaf.direct_image_locale f L.R)) (g# : NatTrans (\suc \lp) M.R (VSheaf.direct_image_locale g L.R)) (p : f = g) (q : \Pi (a : M) (x : M.R a) -> L.R.F.Func (fromHomEq p a) (g# a x) = f# a x) : (\new RingedLocaleHom L M f f#) = (\new RingedLocaleHom L M g g#) \elim p
          | idp => cong $ exts \lam a => exts (\lam x => inv (q a x) *> pmap (\lam (h : RingHom (L.R (f a)) (L.R (f a))) => h (g# a x)) (L.R.F.Func-id {f a}))
      }
  }

\func RingedLocalePrecat : Precat RingedLocale \cowith
  | Hom => RingedLocaleHom
  | id (L : RingedLocale) : RingedLocaleHom L L \cowith {
    | f => FrameCat.id L.L
    | f# => \new NatTrans {
      | trans x => Cat.id _
      | natural p => ext $ pmap (\lam x => func {L.R.F.Func x}) prop-pi
    }
  }
  | o {L M N : RingedLocale} (g : RingedLocaleHom M N) (f : RingedLocaleHom L M) : RingedLocaleHom L N \cowith {
    | f => f.f FrameCat. g.f
    | f# => \new NatTrans {
      | trans x => f.f#.trans (g x)  g.f#.trans x
      | natural {x} {y} p => exts \lam x => path (\lam i => f.f# (g y) (g.f#.natural p i x)) *> path (\lam i => f.f#.natural _ i _)
    }
  }
  | id-left => idp
  | id-right => idp
  | o-assoc => idp
  \where {
    \func forget : Functor RingedLocalePrecat LocaleCat \cowith
      | F L => L
      | Func f => f
      | Func-id => idp
      | Func-o => idp

    \func homMap {L M : RingedLocale} {f g : RingedLocaleHom M L} (p : f = g) (a : L) : RingHom (M.R (f a)) (M.R (g a))
      => M.R.F.Func (Preorder.=_<= (inv (path (\lam i => p i a))))

    \lemma homMap-lem {L M : RingedLocale} {f g : RingedLocaleHom M L} (p : f = g) (a : L) : transport (\lam (h : RingedLocaleHom M L) => RingHom (M.R (f a)) (M.R (h a))) p (RingCat.id _) = homMap p a \elim p
      | idp => inv M.R.F.Func-id *> pmap M.R.F.Func prop-pi

    \lemma homMap-lem2 {L M : RingedLocale} {f g : RingedLocaleHom M L} (p : f = g) (a : L) : homMap p a Cat. homMap (inv p) a = CRingCat.id (M.R (g a)) \elim p
      | idp => inv (pmap2 (Cat.) (homMap-lem idp a) (homMap-lem idp a)) *> id-left

    \func homMap-natural {L M : RingedLocale} {f g : RingedLocaleHom M L} (p : f = g) : NatTrans (Comp M.R f.f.functor.op) (Comp M.R g.f.functor.op) \cowith
      | trans => homMap p
      | natural h => inv M.R.F.Func-o *> pmap M.R.F.Func prop-pi *> M.R.F.Func-o

    \func natTrans-inv {L M : RingedLocale} {e : Iso {RingedLocalePrecat} {L} {M}} (f : NatTrans (\suc \lp) L.R (Comp M.R (Functor.op {FrameHom.functor {e.hinv}})))
      : NatTrans (Comp L.R (Functor.op {FrameHom.functor {e.f}})) M.R \cowith
      | trans x => homMap e.f_hinv x Cat. f (e.f x)
      | natural {a} {b} h =>
        \let t : homMap e.f_hinv b Cat. M.R.F.Func (Func {Functor.op {FrameHom.functor {e.hinv}}} (func-<= {e.f} h)) = M.R.F.Func h Cat. homMap e.f_hinv a
               => pmap (_ Cat. M.R.F.Func __) prop-pi *> natural {homMap-natural e.f_hinv} h *> pmap (Cat.`∘ _) (pmap M.R.F.Func prop-pi)
        \in unfold Func $ rewrite (prop-isProp (Func {Functor.op {FrameHom.functor {e.f}}} h) (func-<= {e.f} h)) $ o-assoc *> rewrite (f.natural (func-<= {e.f} h)) (inv o-assoc *> path (\lam i => t i Cat. f (e.f a)) *> o-assoc)

    \lemma homMap_o {L L' : RingedLocale} (f : RingedLocaleHom L L') (g : RingedLocaleHom L' L) (p : f RingedLocalePrecat. g = id L') (a : L')
      : g.f# (f a) Cat. f.f# a = homMap (inv p) a
      => \have t => simp_coe (simp_coe $ pmapd (\lam (h : RingedLocaleHom L' L') => h.f#) p) a
         \in transport-rotate (\lam (h : RingedLocaleHom L' L') => RingHom (L'.R a) (L'.R (h a))) p t *> homMap-lem (inv p) a

    \lemma homMap_o-right {L L' : RingedLocale} (f : RingedLocaleHom L L') (g : RingedLocaleHom L' L) (p : f RingedLocalePrecat. g = id L') (q : g RingedLocalePrecat. f = id L) (a : L')
      : f.f# a Cat. homMap p a Cat. g.f# (f a) = RingCat.id (L.R (f a))
      => pmap (Cat.`∘ _) (f.f#.natural _) *> CRingCat.o-assoc {L.R (f a)} {L'.R (g (f a))} {L.R (f (g (f a)))} {L.R (f a)} *> rewrite (homMap_o g f q (f a)) (inv L.R.F.Func-o *> pmap L.R.F.Func prop-pi *> L.R.F.Func-id)

    \lemma homMap_o-left {L L' : RingedLocale} (f : RingedLocaleHom L L') (g : RingedLocaleHom L' L) (p : f RingedLocalePrecat. g = id L') (a : L')
      : homMap p a Cat. g.f# (f a) Cat. f.f# a = RingCat.id (L'.R a)
      => o-assoc *> rewrite (homMap_o f g p a) (homMap-lem2 p a)

    \func fromIso {L L' : RingedLocale} (e : Iso {RingedLocalePrecat} {L} {L'}) : Iso {VSheafCat CRingCat L'.L} {VSheaf.direct_image_locale e.f L.R} {L'.R} \cowith
      | f => natTrans-inv (RingedLocaleHom.f# {e.hinv})
      | hinv => RingedLocaleHom.f# {e.f}
      | hinv_f => exts (homMap_o-right e.f e.hinv e.f_hinv e.hinv_f)
      | f_hinv => exts (homMap_o-left e.f e.hinv e.f_hinv)

    \func isotoid (e : Iso {RingedLocalePrecat}) : e.dom = e.cod
      => ext (Cat.isotoid (RingedLocalePrecat.forget.Func-iso e), VSheaf.transport_direct_image-iso _ (RingedLocale.R {e.dom}) *> Cat.isotoid (RingedLocalePrecat.fromIso e))
 }

{-
\instance RingedLocaleCat : Cat RingedLocale
  | Precat => RingedLocalePrecat
  | univalence =>
    Cat.makeUnivalence \lam (e : Iso) => (isotoid e, transport_RingedLocaleHom (isotoid e) (id e.dom) *> ext (someLem6 e, simp_coe $ simp_coe $ someLem5 e)
    )
  \where {
    \open RingedLocalePrecat

    \lemma someLem2 (e : Iso {RingedLocalePrecat}) (a : e.dom) : e.f (transport (Locale.E {__}) (pmap (RingedLocale.L {__}) (isotoid e)) a) = a
      => pmap e.f (someLem3 _ a) *> rewrite (Equiv.f_ret {LocaleCat.univalence {e.dom} {e.cod}} (Functor.Func-iso e)) (pmap (\lam (f : RingedLocaleHom e.dom e.dom) => f a) e.inv_f)

    \lemma someLem3 {L M : Locale} (p : L = M) (a : L) : transport (\lam (X : Locale) => X.E) p a = Iso.inv {Precat.idtoiso p} a \elim p
      | idp => idp

    \lemma someLem5 {L M : RingedLocale} (e : Iso {RingedLocalePrecat} {L} {M}) (a : M) : transport (\lam (h : FrameHom M L) => RingHom (M.R a) (VSheaf.direct_image h (RingedLocale.R {e.dom}) a)) (someLem6 e) (RingedLocaleHom.f# {transportedRLHom (isotoid e) (id e.dom)} a) = RingedLocaleHom.f# {e} a
      => simp_coe $ ext \lam y => simp_coe $ unfold someLem6 $ unfold_let $ transport_*> (\lam (h : FrameHom M L) => L.R (h a)) _ (someLem7 e) _ *> unfold {?}

    \func someLem6 {L M : RingedLocale} (e : Iso {RingedLocalePrecat} {L} {M}) : transport (\lam (X : RingedLocale) => FrameHom X L) (isotoid e) (Cat.id L.L) = RingedLocaleHom.f {e.f}
      => transport_FrameHom (isotoid e) _ *> someLem7 e -- exts (unfold \lam a => unfold {?}) -- simp_coe $ simp_coe \lam a => inv (whatev2 e a)

    \lemma someLem7 {L M : RingedLocale} (e : Iso {RingedLocalePrecat} {L} {M}) : transportedFrameHom (isotoid e) (Cat.id L.L) = RingedLocaleHom.f {e.f}
      => exts \lam a => unfold $ unfold {?}

    \func transportedFrameHom {L M : RingedLocale} {N : Locale} (p : L = M) (f : FrameHom L N) : FrameHom M N \cowith
      | func => transport (\lam (X : RingedLocale) => X -> N) p f -- \lam a => f (transport (\lam (X : RingedLocale) => X) (inv p) a)
      | func-top>= => {?}
      | func-meet => {?}
      | func-Join>= => {?}

    \lemma transport_FrameHom {L M : RingedLocale} {N : Locale} (p : L = M) (f : FrameHom L N) : transport (\lam (X : RingedLocale) => FrameHom X N) p f = transportedFrameHom p f \elim p
      | idp => idp

    \func transportedRLHom {L M N : RingedLocale} (p : L = M) (f : RingedLocaleHom N L) : RingedLocaleHom N M \cowith
      | f => transport (FrameHom __ N) (pmap (RingedLocale.L {__}) p) f.f
      | f# => Jl (\lam (X : RingedLocale) q => NatTrans X.R (VSheaf.direct_image (transport (FrameHom __ N) (pmap (RingedLocale.L {__}) q) f) N.R)) f.f# p

    \func transportedRLHom' {L M N : RingedLocale} (e : Iso {RingedLocalePrecat} {L} {M}) (f : RingedLocaleHom N L) : RingedLocaleHom N M \cowith
      | f => f.f FrameCat.∘ e.f
      | f# => NatTrans.Comp-left f.f# (Functor.op {FrameHom.functor {e.f}}) Cat.∘ RingedLocaleHom.f# {e.f}

    \lemma transport_RingedLocaleHom {L M N : RingedLocale} (p : L = M) (f : RingedLocaleHom N L)
      : transport (RingedLocaleHom N) p f = transportedRLHom p f \elim p
      | idp => idp
  }
-}

\record LocallyRingedLocale \extends RingedLocale
  | isNonTrivial (a : L) : 0 = {R.F a} 1 -> a <= bottom
  | isLocallyRinged (a : L) (x : R.F a) : a <= SJoin (\lam b => \Sigma (p : b <= a) (EitherInv \this p x))
  \where {
    \func EitherInv (L : RingedLocale) {a b : L} (p : b <= a) (x : R.F a)
      => Inv (R.F.Func p x) || Inv (R.F.Func p x + 1)
  }

\record RingedFramePres (\coerce P : FramePres) (R : VSheaf CRingCat (framePresSite P))

\record LocallyRingedFramePres \extends RingedFramePres
  | isNonTrivialPres (a : P) : 0 = {R.F a} 1 -> Cover a absurd
  | isLocallyRingedPres (a : P) (x : R.F a) : FramePres.SCover a (\lam b => \Sigma (p : Cover1 b a) (Inv (R.F.Func p x) || Inv (R.F.Func p x + 1)))
  \where {
    \func EitherInv (P : RingedFramePres) {a b : P} (p : Cover1 b a) (x : R.F a)
      => Inv (R.F.Func p x) || Inv (R.F.Func p x + 1)

    \open sheafOnPresentedFrame
    \open PresentedFrame

    \lemma limInv {P : FramePres} (F : VSheaf CRingBicat (framePresSite P)) (b : P) {y : extend.lim (embed b)} (yi : Inv (y.1 (b, <=-refl))) : Inv y
      => Inv.lmake {extend.lim (embed b)} (\lam j => F.F.Func (embed_Cover j.2) yi.inv, \lam h => inv (pmap (__ yi.inv) $ Func-o {Comp CRingCat.forget F})) $
          exts \lam j => pmap (_ *) (element-lem j) *> inv func-* *> pmap (F.F.Func (embed_Cover j.2)) yi.inv-left *> func-ide
      \where
        \lemma element-lem (j : \Sigma (x : P) (embed x <= embed b)) : y.1 j = F.F.Func (embed_Cover j.2) (y.1 (b, <=-refl))
          => inv $ path (\lam i => func {coneCoh {extend.lim (embed b)} (embed_Cover j.2) i} y)

    \func toPresented {P : RingedFramePres} {a b : P} (p : Cover1 b a) (U : PresentedFrame P) (Ua : U.1 a) (x : extend.lim {P} {CRingBicat} {P.R} U)
      (e : EitherInv P p (x.1 (a, \lam {z} c => U.2 z $ Cover.cover-trans1 c $ cover-inj (a,Ua) idp)))
      : LocallyRingedLocale.EitherInv (ringedLocaleFromPres P) {U} {embed b} (\lam {z} c => U.2 z $ Cover.cover-trans1 c $ Cover.cover-trans1 p $ cover-inj (a,Ua) idp) x \elim e
      | byLeft i => byLeft $ limInv P.R b $ transport Inv (x.2 p) i
      | byRight i => byRight $ limInv P.R b $ transport Inv (pmap (`+ 1) (x.2 p)) i
  }

\func ringedLocaleFromPres (P : RingedFramePres) : RingedLocale \cowith
  | L => PresentedFrame P
  | R => sheafOnPresentedFrame {P} {CRingBicat} P.R

\func locallyRingedLocaleFromPres (P : LocallyRingedFramePres) : LocallyRingedLocale \cowith
  | RingedLocale => ringedLocaleFromPres P
  | isNonTrivial U t {x} Ux => cover-trans (isNonTrivialPres x $ pmap (__.1 (x, \lam {y} c => U.2 y $ Cover.cover-trans1 c $ cover-inj (x,Ux) idp)) t) (\case __)
  | isLocallyRinged U x {a} Ua => cover-trans (isLocallyRingedPres a (x.1 (a, \lam {z} c => U.2 z $ Cover.cover-trans1 c $ cover-inj (a,Ua) idp)))
      \lam t => cover-inj ((PresentedFrame.embed t.1, (\lam {z} c => U.2 z $ Cover.cover-trans1 c $ Cover.cover-trans1 t.2.1 $ cover-inj (a,Ua) idp, LocallyRingedFramePres.toPresented t.2.1 U Ua x t.2.2)), t.1, cover-inj () idp) idp

\func affineRingedPres (R : CRing) : LocallyRingedFramePres (SpecPres R) \cowith
  | R : VSheaf CRingCat (framePresSite (SpecPres R))
    => sheaf-reflect CRingCat.forget CRingCat.forget.reflectsLimit (functor R) $
          sheafOnSiteWithBasis _ $ later \lam x {J} g c => \case \elim c \with {
            | inP (y, x<=y, f, c', q) => FramePres.indexing-transport (\lam {J} e h => \Pi (y : R) (g : J -> SlicePrecat y) -> Cover1 y e -> (\Pi (j : J) -> Cover1 (conj y (h j)) (g j).1) -> Equiv {_} {MatchingFamily y g} (matchingFamily y g))
                (hiding (c',x,J,g,x<=y,q) $ later \case \elim __ \with {
                  | nothing => \lam z ef z<=0 _ => contr-equiv (LocRing.trivial (\case SpecPres.cover_ideal z<=0 \with {
                      | inP (n, inP p) => inP (n, p.2 *> R.BigSum_zro (\lam j => zro_*-right))
                    }) $ later $ inP (1, ide-left)) emptyMatchingFamily
                  | just (a,b) => \lam z g z<=a+b q =>
                    \have | (inP (n,p)) => SpecPres.cover_ideal $ cover-trans1 (cover-prod (cover-inj () idp) z<=a+b) $ cover-trans (cover-ldistr idp (cover-basic $ FramePres.indexing-make $ just (a,b)) (\lam j => idp)) (\lam j => cover-trans1 (q j) $ cover-inj j idp)
                          | (inP (c,d,z^n=g1c+g2d)) => (closure2-lem (\lam j => (g j).1)).1 p
                    \in localization-lem g z^n=g1c+g2d
                }) c' x g x<=y (q __).2
          }
  | isNonTrivialPres a => \lam p => SpecPres.ideal_cover \case LocRing.unequals p \with {
    | inP (c, inP (n,a^n=c), zro=c) => inP (n, inP (nil, equation))
  }
  | isLocallyRingedPres => \lam a (in~ (y,c,inP (n,a^n=c))) => cover-trans1 (SpecPres.cover_pow (suc n)) $
      transport (Cover __ _) (equation : a * negative y + a * (y + pow a n) = pow a (suc n)) $
      cover-trans (cover-basic $ FramePres.indexing-make $ just (a * negative y, a * (y + pow a n))) $ later
        \case \elim __ \with {
          | true =>  cover-inj (_, (cover-proj1 idp () idp, byLeft  $ transportInv Inv                     (functorial-lem-div (\new LDiv { | inv => negative y  | inv-right => idp }) n a^n=c) $ Inv.lmake (inl~ (negative $ pow a (suc n), a * negative y, later $ inP (1, ide-left))) $ LocRing.equals1 $ later $ rewrite CMonoid.pow_*-comm equation)) idp
          | false => cover-inj (_, (cover-proj1 idp () idp, byRight $ transportInv (\lam x => Inv (x + 1)) (functorial-lem-div (\new LDiv { | inv => y + pow a n | inv-right => idp }) n a^n=c) $ Inv.lmake (inl~ (pow a (suc n), a * (y + pow a n), later $ inP (1, ide-left)))         $ LocRing.equals1 $ later $ rewrite CMonoid.pow_*-comm equation)) idp
        }
  \where {
    \open localization
    \open SubMonoid(powers)
    \open sheafOnSiteWithBasis
    \open Cover

    \func functor (R : CRing) => \new Functor (Precat.op {framePresSite (SpecPres R)}) CRingBicat {
      | F a => LocRing (powers a)
      | Func c => (functorial (SpecPres.cover_ideal c)).1
      | Func-id {a} => locMap-epi {_} {_} {LocRing (powers a)} $ (functorial (SpecPres.cover_ideal (id {framePresSite $ SpecPres R} a))).2 *> inv id-left
      | Func-o {a} {b} {c} {g} {f} => locMap-epi {_} {_} {LocRing (powers c)} $ (functorial (SpecPres.cover_ideal (f  {framePresSite $ SpecPres R} g))).2 *>
                                      inv (o-assoc *> pmap (_ RingCat.) (functorial (SpecPres.cover_ideal f)).2 *> (functorial (SpecPres.cover_ideal g)).2)
    }

    \lemma functorial {R : CRing} {a b : R} (r : radical {closure1 a} b)
      : \Sigma (f : RingHom (LocRing (powers a)) (LocRing (powers b))) (f  locMap = locMap)
        \level \lam p q => ext (locMap-epi {_} {_} {LocRing (powers b)} (p.2 *> inv q.2)) \elim r
      | inP (n,p) => \case closure1-lem.1 p \with {
        | inP (c,b^n=ac) =>
          \have a|b^n => \new LDiv a (pow b n) c (inv b^n=ac)
          \in (pow-map b n  div-map a|b^n, o-assoc *> rewrite (div-map_loc a|b^n) (pow-map_loc b n))
      }

    \lemma functorial-lem {R : CRing} {a b : R} {r : radical {closure1 a} b} {x : LocRing.SType (powers a)} (m : Nat) (p : pow a m = x.2) {n : Nat} {c : R} (q : pow b n = a * c)
      : (functorial r).1 (in~ x) = in~ (x.1 * pow c m, pow b (n * m), inP (n * m, idp))
      => localization.map-lemma (functorial r).1 (Inv.lmake (later $ in~ (pow c m, pow b (n * m), inP (n * m, idp))) $
          transportInv (\lam (h : RingHom R (LocRing (powers b))) => _ * h x.2 = 1) (functorial r).2 $ path $ ~-equiv _ _ $ equation {usingOnly (R.pow_* {b} {n} {m}, pmap (pow __ m) q, R.pow_*-comm {a} {c} {m}, p)}) *>
          transportInv (\lam (h : RingHom R (LocRing (powers b))) => h x.1 * _ = _) (functorial r).2 (path $ ~-equiv _ _ equation)

    \lemma functorial-lem-div {R : CRing} {a b : R} (d : LDiv a b) {r : radical {closure1 a} b} {x : LocRing.SType (powers a)} (m : Nat) (p : pow a m = x.2)
      : (functorial r).1 (in~ x) = in~ (x.1 * pow d.inv m, pow b m, inP (m, idp))
      => functorial-lem m p {1} (ide-left *> inv d.inv-right) *> path (~-equiv _ _ $ later $ rewrite ide-left idp)

    \lemma emptyMatchingFamily {C : SiteWithBasis} {F : Functor C.op SetCat} {x : C} {g : Empty -> SlicePrecat x} : Contr (MatchingFamily {C} {F} x g)
      => \new Contr {
        | center => \new MatchingFamily {
          | family => \case __
          | isMatching => \case __
        }
        | contraction mf => exts (\case __)
      }

    \lemma common-denom {R : CRing} {a b : R} (e1 : LocRing (powers a)) (e2 : LocRing (powers b))
      :  (x y : R) (m : Nat) (e1 = in~ (x, pow a m, inP (m,idp))) (e2 = in~ (y, pow b m, inP (m,idp))) \elim e1, e2
      | in~ (x1, d1, inP (m1,a^m1=d1)), in~ (x2, d2, inP (m2,b^m2=d2)) => inP (x1 * pow a m2, x2 * pow b m1, m1 + m2,
          path $ ~-equiv _ _ $ pmap (x1 *) (pow_+ *> *-comm *> pmap (_ *) a^m1=d1) *> inv *-assoc,
          path $ ~-equiv _ _ $ pmap (x2 *) (pow_+ *> pmap (_ *) b^m2=d2) *> inv *-assoc)

    \lemma pow-lin-comb {R : CRing} {a b c d e : R} {k : Nat} (p : pow e k = a * c + b * d) (n m : Nat)
      :  (t s : R) (l : Nat) (pow e l = t * pow a n + s * pow b m) =>
      \have | S => Ideal.closure (pow a n :: pow b m :: nil)
            | I => Ideal.radical {S}
            | (inP (l, q)) => run {
              radical_pow {S}, transportInv I p, contains_+ {I}
                  (ideal-right {I} (inP (n, closureN-lem.2 (inP (1 :: 0 :: nil, equation)))))
                  (ideal-right {I} (inP (m, closureN-lem.2 (inP (0 :: 1 :: nil, equation)))))
            }
            | (inP (:: t (:: s nil), q')) => closureN-lem.1 q
      \in inP (t, s, l, q' *> equation)

    \lemma localization-lem {R : CRing} {e : R} {c d : R} (g : Bool -> SlicePrecat {framePresSite (SpecPres R)} e) {n : Nat} (p : pow e n = (g true).1 * c + (g false).1 * d)
      : Equiv {_} {MatchingFamily _ _} (matchingFamily {_} {Comp CRingCat.forget (functor R)} e g)
      => contrFibers=>Equiv \lam (mf : MatchingFamily) =>
           \have | (inP (n1,t1)) => SpecPres.cover_ideal (g true).2
                 | (inP (c1,a^n1=e*c1)) => closure1-lem.1 t1
                 | (inP (n2,t2)) => SpecPres.cover_ideal (g false).2
                 | (inP (c2,b^n2=e*c2)) => closure1-lem.1 t2
           \in isProp'=>isContr (\lam t1 t2 => ext \case \elim t1, \elim t2 \with {
             | (in~ (y1, _, inP (m1, idp)), coh1), (in~ (y2, _, inP (m2, idp)), coh2) =>
               \case LocRing.unequals $ inv (functorial-lem m1 idp a^n1=e*c1) *> path (\lam i => family {coh1 i} true) *> inv (path (\lam i => family {coh2 i} true)) *> functorial-lem m2 idp a^n1=e*c1,
                     LocRing.unequals $ inv (functorial-lem m1 idp b^n2=e*c2) *> path (\lam i => family {coh1 i} false) *> inv (path (\lam i => family {coh2 i} false)) *> functorial-lem m2 idp b^n2=e*c2 \with {
                 | inP (_, inP (k1, idp), q1), inP (_, inP (k2, idp), q2) =>
                   \have (inP (t,s,l,lc)) => pow-lin-comb p (n1 * m1 + n1 * m2 + k1) (n2 * m1 + n2 * m2 + k2)
                   \in LocRing.equals-lem {_} {powers e} (pow e l) (inP (l,idp)) $ run {
                     repeat {4} (rewrite pow_+) at lc,
                     \have u m : pow (g true).1 (n1 * m) = pow e m * pow c1 m => pow_* *> pmap (pow __ m) a^n1=e*c1 *> R.pow_*-comm,
                     \have v m : pow (g false).1 (n2 * m) = pow e m * pow c2 m => pow_* *> pmap (pow __ m) b^n2=e*c2 *> R.pow_*-comm,
                     equation {using (u m1, u m2, v m1, v m2)}
                   }
               }
           })
           (\let | a => (g true).1
                 | b => (g false).1
            \in \case common-denom (mf.family true) (mf.family false), mf.isMatching true false \with {
              | inP (y1,y2,m,mf1=y1/a^m,mf2=y2/b^m), t =>
                \let | (inP (_, inP (k', idp), coh')) => LocRing.unequals $ inv (pmap (functorial _).1 mf1=y1/a^m *> functorial-lem-div (\new LDiv a (a * b) b idp) m idp) *> t *> pmap (functorial _).1 mf2=y2/b^m *> functorial-lem-div (\new LDiv b (a * b) a *-comm) m idp
                     | k => m + k'
                \in
                \have | coh : y1 * pow b m * pow a k * pow b k = y2 * pow a m * pow a k * pow b k => equation {using (R.pow_+ {a * b} {m} {k'}, R.pow_*-comm {a} {b} {k})}
                      | (inP (u,v,l,lc)) => pow-lin-comb p (m + k) (m + k)
                \in hiding (p,t,k',coh') $ inP (in~ (u * y1 * pow a k + v * y2 * pow b k, pow e l, inP (l, idp)), exts \case \elim __ \with {
                      | true  => functorial-lem l idp a^n1=e*c1 *> LocRing.equals-lem {_} {powers a} (pow a k) (inP (k,idp)) (equation {using (R.pow_* {a} {n1} {l}, pmap (pow __ l) a^n1=e*c1, R.pow_*-comm {e} {c1} {l}, R.pow_+ {a} {m} {k}, R.pow_+ {b} {m} {k})}) *> inv mf1=y1/a^m
                      | false => functorial-lem l idp b^n2=e*c2 *> LocRing.equals-lem {_} {powers b} (pow b k) (inP (k,idp)) (equation {using (R.pow_* {b} {n2} {l}, pmap (pow __ l) b^n2=e*c2, R.pow_*-comm {e} {c2} {l}, R.pow_+ {a} {m} {k}, R.pow_+ {b} {m} {k})}) *> inv mf2=y2/b^m
                    })
            })
  }

\func affineRingedLocale (R : CRing) => locallyRingedLocaleFromPres (affineRingedPres R)

\record Scheme \extends LocallyRingedLocale
  | isScheme : L.top <= SJoin (\lam U =>  (R' : CRing) (VSheaf.restrict U R = {RingedLocale} affineRingedLocale R'))
  | isNonTrivial a p => meet-univ L.top-univ <=-refl <=∘ L.meet-monotone isScheme <=-refl <=∘ L.Join-rdistr>= <=∘ Join-univ (\lam (b, inP (R',q)) =>
      \let t => transportInv (\lam (x : RingedLocale) => \Pi (a : x.L) -> 0 = {x.R.F a} 1 -> a <= bottom) q (isNonTrivial {affineRingedLocale R'})
      \in t (b  a, meet-left) (inv func-zro *> pmap (R.F.Func (meet-right {_} {b})) p *> func-ide) <=∘ Join-univ (\case __))
  | isLocallyRinged a x => meet-univ L.top-univ <=-refl <=∘ L.meet-monotone isScheme <=-refl <=∘ L.Join-rdistr>= <=∘ Join-univ (\lam (b, inP (R',q)) =>
      \let t => transportInv (\lam (x : RingedLocale) => \Pi (a : x.L) (y : x.R.F a) -> a <= SJoin (\lam b => \Sigma (p : b <= a) (LocallyRingedLocale.EitherInv _ p y))) q (isLocallyRinged {affineRingedLocale R'})
      \in t (b  a, meet-left) (R.F.Func meet-right x) <=∘ Join-univ (\lam ((c,c<=b),(c<=ba,e)) => Join-cond $ later (c, (c<=ba <=∘ meet-right, ||.map (transportInv (\lam (f : RingHom (R a) (R c)) => Inv (f x)) R.F.Func-o) (transportInv (\lam (f : RingHom (R a) (R c)) => Inv (f x + 1)) R.F.Func-o) e))))

\func affineScheme (R : CRing) : Scheme \cowith
  | RingedLocale => affineRingedLocale R
  | isScheme {x} _ => cover-inj (((\lam _ => \Sigma, \lam _ _ => ()), inP (R, RingedLocalePrecat.isotoid $ restrict_iso (RingedLocale.R {affineRingedLocale R}))), x, ()) idp
  \where {
    \func locale_iso {L : Locale} : Iso {LocaleCat} {L.restrict L.top} {L} \cowith
      | f => Locale.restrict.map
      | hinv => \new FrameHom {
        | func x => x.1
        | func-top => idp
        | func-meet => idp
        | func-Join => idp
      }
      | hinv_f => exts \lam p => ext L.top-right
      | f_hinv => exts \lam x => L.top-right

    \func restrict_map {L : Locale} (a : L) (S : VSheaf CRingCat L) : RingedLocaleHom (\new RingedLocale (L.restrict a) (VSheaf.restrict a S)) (\new RingedLocale L S) \cowith
      | f => Locale.restrict.map
      | f# => \new NatTrans {
        | trans b => S.F.Func meet-left
        | natural h => inv S.F.Func-o *> pmap S.F.Func prop-pi *> S.F.Func-o
      }

    \func restrict_iso {L : Locale} (S : VSheaf CRingCat L) : Iso {RingedLocalePrecat} {VSheaf.restrict L.top S} {S} \cowith
      | f => restrict_map L.top S
      | hinv : RingedLocaleHom => \new RingedLocaleHom S (VSheaf.restrict L.top S) {
        | f => locale_iso.hinv
        | f# => \new NatTrans {
          | trans p => id _
          | natural h => id-left *> pmap S.F.Func prop-pi *> Paths.inv id-right
        }
      }
      | hinv_f => RingedLocaleHom.ext (hinv RingedLocalePrecat. restrict_map L.top S) _ locale_iso.hinv_f \lam p x => pmap (S.F.Func __ x) prop-pi
      | f_hinv => RingedLocaleHom.ext (restrict_map L.top S RingedLocalePrecat. hinv) _ locale_iso.f_hinv \lam a x => pmap (S.F.Func __ x) prop-pi
  }