{- | The closed interval `[a,b]` and the square `[a,b]²` as cover spaces.
 -
 -   The cover structure of `[a,b]` is transferred from `ℝ` (see {IntervalSpace}).
 -   Constructively, a transferred cover structure need not agree with the transferred metric, but for `[a,b]` they agree
 -   since the inclusion has the uniform retraction {clamp}. Thus maps on `[a,b]²` with an ε-δ modulus are cover maps (see {square-map}),
 -   and cover maps on `[a,b]` and `[a,b]²` are bounded and uniformly continuous
 -   (see {interval-bounded}, {interval-uniform}, {square-bounded}, and {square-uniform}),
 -   and the values of a cover map on `[a,b]` have a supremum and an infimum (see {interval-hasSup} and {interval-hasInf}),
 -   since `[a,b]` is a proper totally bounded uniform space (see {IntervalUniformSpace}).
 -}

\import Algebra.Group
\import Algebra.Meta
\import Algebra.Monoid
\import Algebra.Pointed
\import Arith.Rat
\import Arith.Real
\import Arith.Real.Extremes
\import Arith.Real.Field
\import Function.Meta
\import Logic
\import Logic.Meta
\import Meta
\import Order.Biordered
\import Order.Lattice
\import Order.PartialOrder
\import Order.StrictOrder
\import Paths
\import Paths.Meta
\import Set.Set
\import Topology.Compact
\import Topology.CoverSpace
\import Topology.CoverSpace.Complete
\import Topology.CoverSpace.Product
\import Topology.CoverSpace.Subspace
\import Topology.MetricSpace
\import Topology.MetricSpace.ManhattanProduct
\import Topology.MetricSpace.OpenCover
\import Topology.NormedAbGroup.Real
\import Topology.NormedAbGroup.Real.Compact
\import Topology.NormedAbGroup.Real.Functions
\import Topology.TopRing.Real
\import Topology.TopSpace
\import Topology.UniformSpace

-- | The closed interval `[a,b]`.
\func ClosedInterval (a b : Real) : Set Real
  => \lam x => \Sigma (a <= x) (x <= b)

-- | The closed interval `[a,b]` as a cover space.
\func IntervalSpace (a b : Real) : CoverSpace (Set.Total (ClosedInterval a b))
  => CoverTransfer {Set.Total (ClosedInterval a b)} {RealTopLModule} __.1

-- | The inclusion of `[a,b]` into `ℝ`.
\func intervalInc (a b : Real) : CoverMap (IntervalSpace a b) RealTopLModule __.1
  => CoverTransfer-map __.1

-- | The square `[a,b]²`.
\func SquareSpace (a b : Real) : CoverSpace (\Sigma (Set.Total (ClosedInterval a b)) (Set.Total (ClosedInterval a b)))
  => ProductCoverSpace (IntervalSpace a b) (IntervalSpace a b)

-- | The nearest point of `[a,b]`.
\func clamp {a b : Real} (a<=b : a <= b) (t : Real) : Set.Total (ClosedInterval a b)
  => (a ∨ (t ∧ b), (join-left, join-univ a<=b meet-right))

\lemma clamp-in {a b : Real} {a<=b : a <= b} {t : Real} (p : ClosedInterval a b t) : clamp a<=b t = (t,p)
  => ext (pmap (a ∨) (RealAbGroup.meet_<= p.2) *> RealAbGroup.join_<= p.1)

-- | {clamp} is a cover map.
\lemma clampMap {a b : Real} (a<=b : a <= b) : CoverMap RealNormed (IntervalSpace a b) (clamp a<=b)
  => CoverTransfer-univ (clamp a<=b) __.1 clampReal
  \where
    \lemma clampReal {a b : Real} : CoverMap RealNormed RealNormed (\lam t => a ∨ (t ∧ b))
      => real-join-uniform CoverMap.∘ ProductCoverSpace.tuple (CoverMap.const a) (real-meet-uniform CoverMap.∘ ProductCoverSpace.tuple CoverMap.id (CoverMap.const b))

-- | {clamp} does not increase distances.
\lemma clamp-dist {a b : Real} {a<=b : a <= b} {s t : Real} : RealAbGroup.abs ((clamp a<=b s).1 - (clamp a<=b t).1) <= RealAbGroup.abs (s - t)
  => RealAbGroup.join-univ (half {a} {b} {a<=b} {s} {t}) (transport2 (<=) (inv (AddGroup.negative_- {RealAbGroup} {(clamp a<=b s).1} {(clamp a<=b t).1})) RealAbGroup.abs_- (half {a} {b} {a<=b} {t} {s}))
  \where
    \private \lemma half {a b : Real} {a<=b : a <= b} {s t : Real} : (clamp a<=b s).1 - (clamp a<=b t).1 <= RealAbGroup.abs (s - t)
      => \let D => RealAbGroup.abs (s - t)
         \in \have | D>=0 : 0 <= D => RealAbGroup.abs>=0
                   | sD : s - t <= D => RealAbGroup.abs>=id
                   | m1 : s ∧ b <= s => meet-left
                   | m2 : s ∧ b <= b => meet-right
                   | m : (s ∧ b) - D <= t ∧ b => meet-univ (usingOnly (m1, sD) linarith) (usingOnly (m2, D>=0) linarith)
                   | j1 : a <= a ∨ (t ∧ b) => join-left
                   | j2 : t ∧ b <= a ∨ (t ∧ b) => join-right
                   | j : a ∨ (s ∧ b) <= a ∨ (t ∧ b) + D => join-univ (usingOnly (j1, D>=0) linarith) (usingOnly (m, j2) linarith)
         \in usingOnly j linarith

-- | The plane `ℝ × ℝ` with the sum of the distances; `[a,b]²` is its retract.
\func Plane : PseudoMetricSpace (\Sigma Real Real)
  => ManhattanMetricSpace RealNormed RealNormed
  \where {
    -- | The inclusion of `[a,b]²` into the plane.
    \lemma squareInc {a b : Real} : CoverMap (SquareSpace a b) Plane (\lam p => (p.1.1, p.2.1))
      => ProductCoverSpace.tuple (intervalInc a b CoverMap.∘ ProductCoverSpace.proj1 {IntervalSpace a b} {IntervalSpace a b}) (intervalInc a b CoverMap.∘ ProductCoverSpace.proj2 {IntervalSpace a b} {IntervalSpace a b})

    -- | The retraction of the plane onto `[a,b]²`.
    \lemma squareClamp {a b : Real} (a<=b : a <= b) : CoverMap Plane (SquareSpace a b) (\lam s => (clamp a<=b s.1, clamp a<=b s.2))
      => ProductCoverSpace.tuple (clampMap a<=b CoverMap.∘ ProductCoverSpace.proj1) (clampMap a<=b CoverMap.∘ ProductCoverSpace.proj2)

    \lemma squareClamp-in {a b : Real} {a<=b : a <= b} (p : \Sigma (Set.Total (ClosedInterval a b)) (Set.Total (ClosedInterval a b)))
      : (clamp a<=b p.1.1, clamp a<=b p.2.1) = p
      => pmap2 (__,__) (clamp-in p.1.2) (clamp-in p.2.2)

    -- | Clamping to `[a,b]²` does not increase distances.
    \lemma squareClamp-dist {a b : Real} (a<=b : a <= b) : UniformMetricMap Plane Plane (\lam s => ((clamp a<=b s.1).1, (clamp a<=b s.2).1)) \cowith
      | func-dist-uniform {eps} eps>0 => inP (eps, eps>0, \lam {s} {s'} d => real_<_U.1 (RealAbGroup.<=_+ (clamp-dist {a} {b} {a<=b}) (clamp-dist {a} {b} {a<=b}) <∘r real_<_U.2 d))

    -- | The square `[a,b]²` lies in a ball around `(a,a)`.
    \lemma square-ball (a b : Real) : ∃ (R : Rat) (0 < R) ∀ {x y : Real} (ClosedInterval a b x) (ClosedInterval a b y) (OBall {Plane} R (a,a) (x,y))
      => \case Real.U-inh_>0 {(b - a) RealAbGroup.+ (b - a)} \with {
        | inP (R,Ru,R>0) => inP (R, R>0, \lam {x} {y} xa ya =>
          \have | R' : (b - a) RealAbGroup.+ (b - a) < Real.fromRat R => real_<_U.2 Ru
                | a1 => xa.1
                | a2 => xa.2
                | a3 => ya.1
                | a4 => ya.2
                | u1 : a - x <= b - a => linarith
                | u2 : negative (a - x) <= b - a => linarith
                | v1 : a - y <= b - a => linarith
                | v2 : negative (a - y) <= b - a => linarith
                | bx : RealAbGroup.abs (a - x) <= b - a => RealAbGroup.join-univ u1 u2
                | by : RealAbGroup.abs (a - y) <= b - a => RealAbGroup.join-univ v1 v2
          \in real_<_U.1 (linarith : RealAbGroup.abs (a - x) RealAbGroup.+ RealAbGroup.abs (a - y) < Real.fromRat R))
      }
  }

-- | A function on `[a,b]²` which is uniformly continuous with respect to the sum of the distances is a cover map.
\lemma square-map {a b : Real} (a<=b : a <= b) {h : \Sigma (Set.Total (ClosedInterval a b)) (Set.Total (ClosedInterval a b)) -> Real}
                  (hu : ∀ {eps : Rat} (0 < eps) ∃ (delta : Rat) (0 < delta) ∀ {x y x' y' : Set.Total (ClosedInterval a b)}
                          (RealAbGroup.abs (x.1 - x'.1) + RealAbGroup.abs (y.1 - y'.1) < Real.fromRat delta) (RealAbGroup.abs (h (x,y) - h (x',y')) < Real.fromRat eps))
  : CoverMap (SquareSpace a b) RealNormed h
  => retract-coverMap {SquareSpace a b} {Plane} {RealNormed} Plane.squareInc (\lam s => (clamp a<=b s.1, clamp a<=b s.2)) Plane.squareClamp-in (Plane.squareClamp-dist a<=b)
      \lam eps>0 => \case hu eps>0 \with {
        | inP (delta,delta>0,hd) => inP (delta, delta>0, \lam {p} {p'} d => real_<_U.1 (hd {p.1} {p.2} {p'.1} {p'.2} (real_<_U.2 d)))
      }

-- | A cover map on `[a,b]²` is bounded.
\lemma square-bounded {a b : Real} (a<=b : a <= b) (g : CoverMap (SquareSpace a b) RealNormed)
  : ∃ (M : Rat) (0 < M) (\Pi (p : \Sigma (Set.Total (ClosedInterval a b)) (Set.Total (ClosedInterval a b))) -> RealAbGroup.abs (g p) <= Real.fromRat M)
  => \case plane-bounded (g CoverMap.∘ Plane.squareClamp a<=b) a b \with {
    | inP (M,M>0,h) => inP (M, M>0, \lam p => transport (\lam z => RealAbGroup.abs (g z) <= _) (Plane.squareClamp-in p) (h p.1.2 p.2.2))
  }
  \where
    \lemma plane-bounded (g : CoverMap Plane RealNormed) (a b : Real)
      : ∃ (M : Rat) (0 < M) ∀ {x y : Real} (ClosedInterval a b x) (ClosedInterval a b y) (RealAbGroup.abs (g (x,y)) <= M)
      => \case Plane.square-ball a b \with {
        | inP (R,R>0,sq) => \case openCover-bounded {Plane} {top} (open-top {Plane}) (g CoverMap.∘ OpenCoverSpace.func {Plane} {top} (open-top {Plane}))
                                     (manhattan-ballsTB real-bounded-tb real-bounded-tb (a,a) R>0) (ball-<=* RatField.zro<ide \lam _ _ => ()) \with {
          | inP (M,M>0,h) => inP (M, M>0, \lam {x} {y} xa ya => h {(x,y),()} (sq xa ya))
        }
      }

-- | A cover map on `[a,b]²` is uniformly continuous.
\lemma square-uniform {a b : Real} (a<=b : a <= b) (g : CoverMap (SquareSpace a b) RealNormed) {eps : Rat} (eps>0 : 0 < eps)
  : ∃ (delta : Rat) (0 < delta) ∀ {x y x' y' : Set.Total (ClosedInterval a b)}
      (RealAbGroup.abs (x.1 - x'.1) + RealAbGroup.abs (y.1 - y'.1) < Real.fromRat delta) (RealAbGroup.abs (g (x,y) - g (x',y')) < Real.fromRat eps)
  => \case plane-uniform (g CoverMap.∘ Plane.squareClamp a<=b) a b eps>0 \with {
    | inP (delta,delta>0,h) => inP (delta, delta>0, \lam {x} {y} {x'} {y'} d =>
        transport2 (\lam p q => RealAbGroup.abs (g p - g q) < _) (Plane.squareClamp-in (x,y)) (Plane.squareClamp-in (x',y')) (h x.2 y.2 x'.2 y'.2 d))
  }
  \where
    \lemma plane-uniform (g : CoverMap Plane RealNormed) (a b : Real) {eps : Rat} (eps>0 : 0 < eps)
      : ∃ (delta : Rat) (0 < delta) ∀ {x y x' y' : Real} (ClosedInterval a b x) (ClosedInterval a b y) (ClosedInterval a b x') (ClosedInterval a b y')
          (RealAbGroup.abs (x - x') RealAbGroup.+ RealAbGroup.abs (y - y') < delta) (RealAbGroup.abs (g (x,y) - g (x',y')) < eps)
      => \case Plane.square-ball a b \with {
        | inP (R,R>0,sq) => \case cover-uniform-ball (manhattan-ballsTB real-bounded-tb real-bounded-tb) g (a,a) R>0 eps>0 \with {
          | inP (d,d>0,h) => inP (d, d>0, \lam xa ya xa' ya' dd => real_<_U.2 (h (sq xa ya) (sq xa' ya') (real_<_U.1 dd)))
        }
      }

-- | A cover map on `[a,b]` is bounded.
\lemma interval-bounded {a b : Real} (a<=b : a <= b) (g : CoverMap (IntervalSpace a b) RealNormed)
  : ∃ (M : Rat) (0 < M) (\Pi (x : Set.Total (ClosedInterval a b)) -> RealAbGroup.abs (g x) <= Real.fromRat M)
  => \case square-bounded a<=b (g CoverMap.∘ ProductCoverSpace.proj1 {IntervalSpace a b} {IntervalSpace a b}) \with {
    | inP (M,M>0,h) => inP (M, M>0, \lam x => h (x,x))
  }

-- | A cover map on `[a,b]` is uniformly continuous.
\lemma interval-uniform {a b : Real} (a<=b : a <= b) (g : CoverMap (IntervalSpace a b) RealNormed) {eps : Rat} (eps>0 : 0 < eps)
  : ∃ (delta : Rat) (0 < delta) ∀ {x y : Set.Total (ClosedInterval a b)} (RealAbGroup.abs (y.1 - x.1) < Real.fromRat delta) (RealAbGroup.abs (g y - g x) <= Real.fromRat eps)
  => \case square-uniform a<=b (g CoverMap.∘ ProductCoverSpace.proj1 {IntervalSpace a b} {IntervalSpace a b}) eps>0 \with {
    | inP (delta,delta>0,hd) => inP (delta, delta>0, \lam {x} {y} d =>
      \have d' : RealAbGroup.abs (y.1 - x.1) + RealAbGroup.abs (x.1 - x.1) < Real.fromRat delta
            => transportInv (< _) (pmap (_ +) (pmap RealAbGroup.abs negative-right *> RealAbGroup.abs_zro) *> zro-right) d
      \in <=-less (hd {y} {x} {x} {x} d'))
  }

-- | The closed interval `[a,b]` as a uniform space; its underlying cover space is {IntervalSpace}.
\func IntervalUniformSpace (a b : Real) : UniformSpace (Set.Total (ClosedInterval a b))
  => UniformTransfer {Set.Total (ClosedInterval a b)} {RealNormed} __.1

-- | `[a,b]` is totally bounded.
\lemma intervalUniform-totallyBounded {a b : Real} : IsTotallyBounded (IntervalUniformSpace a b)
  => transfer-totallyBounded {_} {_} {__.1} interval-tb __.2
  \where
    \lemma interval-tb {a b : Real} : IsTotallyBoundedSet (ClosedInterval a b)
      => \case Real.U-inh_>0 {b - a} \with {
        | inP (R,Ru,R>0) => ballsTB-totallyBounded real-bounded-tb $ inP (a, R, \lam {x} (Kx : ClosedInterval a b x) =>
          \have | x1 => Kx.1
                | x2 => Kx.2
                | u1 : a - x <= b - a => linarith
                | u2 : negative (a - x) <= b - a => linarith
          \in real_<_U.1 (RealAbGroup.join-univ u1 u2 <∘r real_<_U.2 Ru))
      }

-- | `[a,b]` is a proper uniform space.
\lemma intervalUniform-proper {a b : Real} (a<=b : a <= b) : (IntervalUniformSpace a b).IsProperUniform
  => retract-proper RealNormed.metricProperUniform (UniformTransfer-map __.1) (clampUniform a<=b) \lam x => clamp-in x.2
  \where {
    -- | {clamp} is a uniform map.
    \lemma clampUniform {a b : Real} (a<=b : a <= b) : UniformMap RealNormed (IntervalUniformSpace a b) (clamp a<=b)
      => UniformMap.lift (UniformTransfer-map __.1) (\lam Cu => Cu) (clampMetric a<=b)

    \lemma clampMetric {a b : Real} (a<=b : a <= b) : UniformMetricMap RealNormed RealNormed (\lam t => (clamp a<=b t).1) \cowith
      | func-dist-uniform {eps} eps>0 => inP (eps, eps>0, \lam {s} {s'} d => real_<_U.1 (clamp-dist {a} {b} {a<=b} {s} {s'} <∘r real_<_U.2 d))
  }

-- | The values of a cover map on `[a,b]` have a supremum (Bishop–Bridges, Ch. 2, Prop. 4.6).
\lemma interval-hasSup {a b : Real} (a<=b : a <= b) (g : CoverMap (IntervalSpace a b) RealNormed)
  : HasSup (\lam r => ∃ (x : Set.Total (ClosedInterval a b)) (g x = r))
  => totallyBounded-hasSup {IntervalUniformSpace a b} (intervalUniform-proper a<=b) intervalUniform-totallyBounded (a, (<=-refl, a<=b)) g

-- | The values of a cover map on `[a,b]` have an infimum (Bishop–Bridges, Ch. 2, Prop. 4.6).
\lemma interval-hasInf {a b : Real} (a<=b : a <= b) (g : CoverMap (IntervalSpace a b) RealNormed)
  : HasInf (\lam r => ∃ (x : Set.Total (ClosedInterval a b)) (g x = r))
  => totallyBounded-hasInf {IntervalUniformSpace a b} (intervalUniform-proper a<=b) intervalUniform-totallyBounded (a, (<=-refl, a<=b)) g