\import Algebra.Field
\import Algebra.Field.AlgebraicClosure
\import Algebra.Group
\import Algebra.Meta
\import Algebra.Monoid
\import Algebra.Ordered
\import Algebra.Pointed
\import Algebra.Ring.Integral
\import Algebra.Ring.Poly
\import Algebra.Ring.Poly.Derivative
\import Algebra.Ring.Poly.Separable
\import Algebra.Ring.RingHom
\import Algebra.Ring.SubRing
\import Algebra.Semiring
\import Algebra.StrictlyOrdered
\import Analysis.Poly (coefMax, coefMax-cond, coefMax>=0)
\import Arith.Algebraic
\import Arith.Algebraic.Newton
\import Arith.Algebraic.Separable
\import Arith.Complex
\import Arith.Complex.FTA.Approximation (fta-approx-eps)
\import Arith.Complex.FTA.Moduli (cabs_polyEval-small-disc)
\import Arith.Complex.Norm
\import Arith.Nat
\import Arith.Rat
\import Arith.Real
\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
\open PosetSemiring (<=_*_positive_positive)
\open LinearlyOrderedSemiring (<=_*-cancel-right)

{- | **The fundamental theorem of algebra without choice**: for separable complex polynomials, and
     hence over any discretely-presented subfield of $\mathbb{C}$.

     `Arith.Complex.FTA.Classical` extracts a root of an arbitrary monic complex polynomial at the
     cost of countable choice, and Richman's thesis is that the cost is unavoidable: one cannot
     solve even a quadratic pointwise without it. The **separable** case is choice-free, and
     `separable-root` is that theorem: locate an approximate root with `fta-approx-eps`, use
     separability to bound the derivative away from zero there (`separable-deriv-lower`), and
     sharpen the approximation to an exact root with `newton-root`.

     `FTA-discrete` draws the consequence for a discrete subfield of $\mathbb{C}$. Discreteness is
     used twice: it lets the Euclidean algorithm run, so `separable-factor` produces a separable
     factor of any nonconstant polynomial, and it makes leading coefficients invertible, so a monic
     associate exists as data rather than merely provably. Characteristic zero needs no hypothesis
     — `subfield-char0` reads it off the embedding.

     This is the theorem Richman points at in *The fundamental theorem of algebra: a constructive
     development without choice* (Pacific J. Math. 196(1), 2000) when he says the algebraic case
     follows "by very general algebraic considerations". -}

-- # The separable case

{- | **A separable complex polynomial with a monic associate has a root** — choice-free. The
     confining radius comes from the Cauchy root bound `cabs_polyEval-small-disc`, which places
     every point where a monic polynomial has modulus at most `1` inside an explicit disc. -}
\lemma separable-root {q : Poly ComplexField} (sep : IsSeparable q) {m : Nat}
    (deg : degree< q (suc (suc m))) (ci : Monoid.Inv (polyCoef q (suc m)))
  : ∃ (z : Complex) (polyEval q z = 0)
  => \let | q1 => ci.inv PolyRing.*c q
          | Cq => coefMax {ComplexValuedRing} (q1 - monomial 1 (suc m)) (suc m)
          | Cq>=0 : (0 : Real) <= Cq
             => coefMax>=0 {ComplexValuedRing} {q1 - monomial 1 (suc m)} {suc m}
          | n>=0 => RealField.natCoef>=0 {suc m}
     \in separable-root-radius sep deg (degree<_*c deg) (polyCoef_*c *> ci.inv-left) (cabs>0_Inv.2 ci.reverse) idp (2 + (1 + Cq) * natCoef (suc m))
           (linarith (<=_*_positive_positive (linarith : (0 : Real) <= 1 + Cq) n>=0))
           (\lam z hz => cabs_polyEval-small-disc q1 (degree<_*c deg) (polyCoef_*c *> ci.inv-left) Cq>=0
                           (coefMax-cond {ComplexValuedRing}) (linarith : (0 : Real) <= 1) hz)
  \where \private {
    -- | If $Dx > 0$ for some $D > 0$, then $x > 0$.
    \lemma pos-factor {D x : Real} (D>0 : 0 < D) (h : 0 < D * x) : 0 < x
      => RealField.pos_>0 (RealField.pos_*-cancel-left (RealField.>0_pos h) (RealField.>0_pos D>0))

    {- | **The quantitative core: approximate root, then Newton.** Every constant is a parameter and
         every smallness condition a hypothesis; `separable-root-radius` discharges them.

         `q1` is a monic associate of `q`, that is `gamma * q` for an invertible scalar `gamma`:
         `fta-approx-eps` and the root bound need monicity, while separability and Newton are stated
         for `q` itself. -}
    \lemma separable-root-aux {q q1 : Poly ComplexField} {m : Nat}
        (deg : degree< q (suc (suc m)))
        (deg1 : degree< q1 (suc (suc m))) (monic : polyCoef q1 (suc m) = 1)
        {gamma : Complex} (g>0 : 0 < cabs gamma) (hq1 : q1 = gamma PolyRing.*c q)
        {R R0 : Real} (hR0 : \Pi (z : Complex) -> cabs (polyEval q1 z) <= 1 -> cabs z <= R0)
        (hRR : R = R0 + 1)
        {delta D : Real} (D>0 : 0 < D)
        (bound : \Pi (z : Complex) -> cabs z <= R -> cabs (polyEval q z) <= delta
                 -> (ratio 1 2 : Real) <= D * cabs (polyEval (polyDeriv q) z))
        {B e0 : Real} (B>0 : 0 < B) (B<1 : B < 1) (e0>0 : 0 < e0) (e0<=delta : e0 <= delta)
        (hB : e0 * (D + D) + e0 * (D + D) <= B)
        (hL : coefMax {ComplexValuedRing} (polyDeriv q) (suc (suc m))
              * RealField.powSum R (suc (suc m)) * RealField.powSum R (suc (suc m)) * B * (D + D) <= (ratio 1 4 : Real))
        (hC : coefMax {ComplexValuedRing} q (suc (suc m)) * RealField.powSum R (suc (suc m))
              * RealField.powSum R (suc (suc m)) * RealField.powSum R (suc (suc m)) * ((D + D) * (D + D)) * e0
              <= (ratio 1 4 : Real))
      : ∃ (z : Complex) (polyEval q z = 0)
      => \let | (inP (z0, hz0)) => fta-approx-eps NatOrder.zero<suc q1 deg1 monic (positivity : 0 < cabs gamma * e0 ∧ 1)
              | b0 => polyEval (polyDeriv q) z0
         \in \have
           | scale : cabs (polyEval q1 z0) = cabs gamma * cabs (polyEval q z0)
              => pmap cabs (pmap (polyEval __ z0) hq1 *> polyEvalRingHom.polyEval_*c)
                 *> cabs_* {gamma} {polyEval q z0}
           | hqz : cabs (polyEval q z0) <= e0
              => <=_*-cancel-right g>0 (=_<= (*-comm *> inv scale)
                                        <=∘ <=-less (hz0 <∘l meet-left)
                                        <=∘ =_<= *-comm)
           | hz0R0 : cabs z0 <= R0 => hR0 z0 (<=-less (hz0 <∘l meet-right))
           | low : (ratio 1 2 : Real) <= D * cabs b0
              => bound z0 (hz0R0 <=∘ (linarith : R0 <= R)) (hqz <=∘ e0<=delta)
           | dpos : 0 < cabs b0 => pos-factor D>0 (usingOnly low linarith)
           | iv : Monoid.Inv b0 => cabs>0_Inv.1 dpos
           | hdinv : cabs iv.inv <= D + D
              => <=_*-cancel-right dpos
                   (=_<= (inv (cabs_* {iv.inv} {b0}) *> pmap cabs iv.inv-left *> cabs_ide)
                    <=∘ (usingOnly low linarith : (1 : Real) <= D * cabs b0 + D * cabs b0)
                    <=∘ =_<= (inv (equation.cRing
                                   : (D + D) * cabs b0 = D * cabs b0 + D * cabs b0)))
         \in newton-root deg iv.inv-right hz0R0 (linarith : R0 + B <= R) (<=-less B>0)
               hdinv hqz (<=-less e0>0) hB hL hC

    {- | **Choosing the constants.** Shrink `B` until the derivative's drift across the ball costs at
         most $1/4$; then shrink `e0` until the geometric-series budget and the quadratic remainder
         both fit. The constants are not optimal — $1/4$ twice is simply the easiest pair to verify.

         Stated over abstract reals because `linarith` cannot distribute a product over a sum: each
         hypothesis has to reach it already flattened, which is only convenient where every quantity is
         a variable. -}
    \lemma choose-constants {Lc Cc Dd delta : Real} (Lc>=0 : 0 <= Lc) (Cc>=0 : 0 <= Cc)
        (Dd>=0 : 0 <= Dd) (delta>0 : 0 < delta)
      : ∃ (B : Real) (0 < B) (B < 1) (e0 : Real) (0 < e0) (e0 <= delta)
          (e0 * Dd + e0 * Dd <= B) (Lc * B * Dd <= (ratio 1 4 : Real))
          (Cc * (Dd * Dd) * e0 <= (ratio 1 4 : Real))
      => \let | CD>=0 : 0 <= Cc * (Dd * Dd) => positivity
              | (inP (B, B>0, hd)) => split-eps (positivity : (0 : Real) < ratio 1 4) (positivity : 0 < Lc * Dd + 1)
              | (inP (e1, e1>0, he)) => split-eps B>0 (positivity : 0 < Dd + Dd + Cc * (Dd * Dd) + 1)
         \in \have
           | BL>=0 : (0 : Real) <= B * (Lc * Dd)
              => <=_*_positive_positive (<=-less B>0) (<=_*_positive_positive Lc>=0 Dd>=0)
           | hd' : B * (Lc * Dd) + B < (ratio 1 4 : Real)
              => rewriteI (equation.cRing : B * (Lc * Dd + 1) = B * (Lc * Dd) + B) hd
           | eC>=0 : (0 : Real) <= e1 * (Cc * (Dd * Dd))
              => <=_*_positive_positive (<=-less e1>0) CD>=0
           | eD>=0 : (0 : Real) <= e1 * Dd => <=_*_positive_positive (<=-less e1>0) Dd>=0
           | he' : e1 * Dd + e1 * Dd + e1 * (Cc * (Dd * Dd)) + e1 < B
              => rewriteI (equation.cRing : e1 * (Dd + Dd + Cc * (Dd * Dd) + 1)
                                          = e1 * Dd + e1 * Dd + e1 * (Cc * (Dd * Dd)) + e1) he
           | e0<=e1 : e1 ∧ delta <= e1 => meet-left
         \in inP (B, B>0, usingOnly (hd', BL>=0) linarith,
                  e1 ∧ delta, <_meet-univ e1>0 delta>0, meet-right,
                  usingOnly (<=_*_positive-left e0<=e1 Dd>=0, he', eC>=0, e1>0) linarith,
                  =_<= (equation.cRing : Lc * B * Dd = B * (Lc * Dd))
                    <=∘ usingOnly (hd', BL>=0, B>0) linarith,
                  <=_*_positive-right CD>=0 e0<=e1
                    <=∘ =_<= (equation.cRing : Cc * (Dd * Dd) * e1 = e1 * (Cc * (Dd * Dd)))
                    <=∘ usingOnly (he', eD>=0, e1>0, hd', BL>=0) linarith)

    {- | `separable-root` with the confining radius supplied by the caller: `R0` must contain every
         point where the monic associate `q1` has modulus at most `1`. -}
    \lemma separable-root-radius {q q1 : Poly ComplexField} (sep : IsSeparable q) {m : Nat}
        (deg : degree< q (suc (suc m)))
        (deg1 : degree< q1 (suc (suc m))) (monic : polyCoef q1 (suc m) = 1)
        {gamma : Complex} (g>0 : 0 < cabs gamma) (hq1 : q1 = gamma PolyRing.*c q)
        (R0 : Real) (R0>=0 : 0 <= R0)
        (hR0 : \Pi (z : Complex) -> cabs (polyEval q1 z) <= 1 -> cabs z <= R0)
      : ∃ (z : Complex) (polyEval q z = 0)
      => \let | (inP (delta, delta>0, D, D>0, bound)) => separable-deriv-lower sep (positivity : 0 <= R0 + 1)
              | P>=0 : (0 : Real) <= RealField.powSum (R0 + 1) (suc (suc m))
                     => RealField.powSum>=0 (positivity : 0 <= R0 + 1) (suc (suc m))
              | (inP (B, B>0, B<1, e0, e0>0, e0<=delta, hB, hL, hC)) =>
                  choose-constants
                    (<=_*_positive_positive (<=_*_positive_positive
                       (coefMax>=0 {ComplexValuedRing} {polyDeriv q} {suc (suc m)}) P>=0) P>=0)
                    (<=_*_positive_positive (<=_*_positive_positive (<=_*_positive_positive
                       (coefMax>=0 {ComplexValuedRing} {q} {suc (suc m)}) P>=0) P>=0) P>=0)
                    (positivity : 0 <= D + D) delta>0
         \in separable-root-aux deg deg1 monic g>0 hq1 hR0 idp D>0 bound
               B>0 B<1 e0>0 e0<=delta hB hL hC
  }

-- # Discrete subfields of the complex numbers

{- | **FTA over a discrete subfield of $\mathbb{C}$.** Unlike the statement over $\mathbb{C}$
     itself, neither monicity nor a `degree<` bound is assumed: discreteness makes the degree
     computable, so $\deg p = n+1$ is the whole nonconstancy hypothesis, and it makes the leading
     coefficient invertible, so the monic associate that `fta-approx-eps` needs can be produced.

     The root comes with its integrality over `K`, the witness being `p` itself. -}
\lemma FTA-discrete {K : DiscreteField} (f : RingHom K ComplexField) {p : Poly K} {n : Nat} (dp : degree p = suc n)
  : ∃ (z : Complex) (polyEval (polyMap f p) z = 0) (isIntegral f z)
  => \let | p/=0 => degree-suc/=0 dp
          | (inP (q, dq>0, sep, ld)) => separable-factor (subfield-char0 f) p/=0 dp
          | q/=0 => (LDiv/=0 ld p/=0).1
     \in cases (degree q arg addPath) \with {
       | 0, e => absurd (\case rewrite e in dq>0 \with {})
       | suc m, e =>
         \let | dq2 : degree< q (suc (suc m))
                 => degree_degree< {K} {q} {suc (suc m)}
                      (rewrite e (linarith : suc m < suc (suc m)))
              | (inP (z, hz)) => separable-root (IsSeparable_polyMap sep) (degree<_polyMap dq2)
                    (transportInv Monoid.Inv polyCoef_polyMap (f.func-Inv (degree-lead-Inv q/=0 e)))
              | pe : polyEval (polyMap f p) z = 0
                 => polyEval_LDiv ((polyMapRingHom f).func-LDiv ld) hz
         \in inP (z, pe,
                  isIntegral.fromInv {K} {ComplexField} {f} {z} {p} {suc n}
                    (degree_degree<= {K} {p} {suc n} (rewrite dp <=-refl))
                    (degree-lead-Inv p/=0 dp) pe)
     }

{- | **Every nonconstant rational polynomial has a complex root, and that root is algebraic.** The
     $\mathbb{Q}$ case of `FTA-discrete`, literally so, since `IsAlgebraic` *is* integrality over
     $\mathbb{Q}$. -}
\lemma FTA-rat {p : Poly RatField} {n : Nat} (dp : degree p = suc n)
  : ∃ (z : Complex) (polyEval (polyMap ratToComplex p) z = 0) (IsAlgNumber z)
  => TruncP.map (FTA-discrete ratToComplex dp) \lam s => (s.1,s.2,s.3)

{- | **FTA for the algebraic numbers.** $\mathbb{A}$ is discrete, so `FTA-discrete` returns a
     complex root integral over $\mathbb{A}$; $\mathbb{A}$ is integrally closed in $\mathbb{C}$, so
     that root is an algebraic number, and injectivity of the inclusion transports $p(z) = 0$ back
     down. -}
\lemma FTA-algNumbers {p : Poly AlgNumbersRing} {n : Nat} (dp : degree {AlgNumbersField} p = suc n)
  : ∃ (z : AlgNumbersRing) (polyEval p z = 0)
  => \let | (inP (z, pe, zi)) => FTA-discrete {AlgNumbersField} algNumbersToComplex dp
          | (inP (b, hb)) => integralClosure-closed ratToComplex z zi
     \in inP (b, algNumbersToComplex.isInj
                   (inv polyEval_polyMap
                    *> pmap (polyEval (polyMap algNumbersToComplex p)) hb *> pe
                    *> inv algNumbersToComplex.func-zro))

\lemma algNumbers-algClosed : IsAlgebraicallyClosed AlgNumbersRing
  => \lam {p} => \case \elim __ \with {
    | inP (0,c,_,_) => absurd (c idp)
    | inP (suc n, _, d, c) => FTA-algNumbers $ <=-antisymmetric (degree<=_degree d) $ degree-coef/=0 $
                                transportInv (/= 0) c (/=-sym AlgNumbersField.zro/=ide)
  }