ogdoad 1.0.0

Clifford algebras (with nilpotents) over the field-like subclasses of combinatorial games: nimbers, surreals, surcomplex.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
//! Places, the Hilbert symbol, and Hilbert reciprocity over the **global function
//! field** `F_q(t)` — the equal-characteristic (char `p`) mirror of
//! [`forms::padic`](crate::forms) over `ℚ`.
//!
//! `F_q(t)` is a global field exactly like `ℚ`, with one structural simplification
//! and one structural difference:
//!
//!   * **simpler:** `q` is odd, so *every* residue field `κ(π) = F_q[t]/(π) =
//!     F_{q^{deg π}}` has odd characteristic. The Hilbert symbol is therefore the
//!     **tame symbol** at every place — there is **no `p = 2` branch** (the messy
//!     mod-8 case that `local_global/padic.rs` carries). The residue-characteristic-2 boundary
//!     is the `springer_laurent` boundary; char-2 function fields are out of scope.
//!   * **different:** there is **no archimedean place**. The role of `ℝ` is played
//!     by the **degree place `∞`** (uniformizer `1/t`, residue field `F_q`), which
//!     is just another tame place — so Hasse–Minkowski over `F_q(t)` has no
//!     definiteness condition (see
//!     [`try_is_isotropic_ff`]).
//!
//! The places of `F_q(t)`: the **finite** places are the monic irreducible
//! polynomials `π(t) ∈ F_q[t]` (residue field `F_{q^{deg π}}`), and the one
//! **infinite** place `∞` is the degree valuation `v_∞(f) = deg(den) − deg(num)`.
//! Reciprocity `∏_v (a,b)_v = +1` (Weil) is the gold oracle, exact here.
//!
//! Entries are elements of [`RationalFunction`] `= F_q(t)`; everything reduces to
//! [`Poly`] arithmetic over `F_q`, with the residue quadratic character computed by
//! Euler's criterion `u^{(|κ|−1)/2}` in `F_q[t]/(π)`. Bridge K's tame Kummer helpers
//! use the same place data, replacing the quadratic character by the full tame symbol
//! when `μ_n` already lives in the constant field.

use crate::forms::{is_square_finite, FiniteOddField};
use crate::scalar::{Poly, Rational, RationalFunction, Scalar};

/// A place of the rational function field `F_q(t)`: the degree place `∞`, or a finite
/// place given by a monic irreducible `π(t)`. The mirror of
/// [`Place`](crate::forms::Place)`{Real,Prime}` over `ℚ`.
///
/// One type for **both** characteristic regimes: the odd-`q` tame-symbol layer here
/// and the characteristic-2 Artin–Schreier layer in
/// [`function_field_char2`](crate::forms) share the *same*
/// places — the structural payload (a uniformizer, finite or the degree place) does
/// not depend on the residue characteristic. The type is generic over `S: Scalar`;
/// the residue-arithmetic bounds (`FiniteOddField` / `FiniteChar2Field`) stay on the
/// functions and impls that read the residue field, not on the place itself.
///
/// **Precondition on `Finite`:** the payload must be a monic irreducible polynomial
/// over `F_q` — that is what makes `κ = F_q[t]/(π)` a field, so that `q^{deg π}` is a
/// genuine field order (the assumption every `try_kappa_order`-rooted symbol function
/// below makes). The type does not check this at construction: a full irreducibility
/// test costs a factorization, which every place-*producing* function here
/// ([`try_relevant_places_ff`], [`monic_irreducible_factors`]) already pays once, so
/// paying it again on every symbol call would be a needless per-call cost on the hot
/// path. Passing a reducible or non-monic `Finite` payload to a symbol/valuation
/// function (`try_kappa_order`, [`try_valuation_at_ff`], `try_residue_unit_at`,
/// `try_chi_kappa`, [`try_hilbert_symbol_ff`], …) is silently accepted and produces
/// a **meaningless**, not erroneous, result; `try_kappa_order` and
/// [`try_valuation_at_ff`] — the two base entry points every other function in this
/// module routes through — `debug_assert!` the precondition, so violations panic in
/// debug/test builds and are free in release. The one uncontrolled input boundary,
/// `py::forms::parse_ff_place`, checks irreducibility unconditionally instead, since
/// it cannot rely on the caller having produced the place via factorization.
#[derive(Debug, Clone, PartialEq)]
pub enum FunctionFieldPlace<S: Scalar> {
    /// The degree place `∞` (uniformizer `1/t`, residue field `F_q`).
    Infinite,
    /// A finite place: a monic irreducible `π(t)` (residue field `F_q[t]/(π)`).
    Finite(Poly<S>),
}

impl<S: Scalar> Eq for FunctionFieldPlace<S> {}

impl<S: Scalar> std::fmt::Display for FunctionFieldPlace<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            FunctionFieldPlace::Infinite => f.write_str(""),
            FunctionFieldPlace::Finite(pi) => write!(f, "{pi}"),
        }
    }
}

// ───────────────────────── factorization over F_q ─────────────────────────

/// The distinct monic irreducible factors of `f` over `F_q` (the square-free
/// support — multiplicities dropped, which is all the place layer needs).
pub fn monic_irreducible_factors<S: FiniteOddField>(f: &Poly<S>) -> Vec<Poly<S>> {
    crate::forms::poly_factor::monic_irreducible_factor_support(
        f,
        S::characteristic_prime(),
        S::field_order(),
        S::from_index,
    )
}

/// The multiplicity of `pi` in `p` (and `p` with all those factors stripped).
fn strip_factor<S: Scalar>(mut p: Poly<S>, pi: &Poly<S>) -> (i128, Poly<S>) {
    let mut mult = 0i128;
    if p.is_zero() {
        return (0, p);
    }
    loop {
        let (quot, rem) = p.divrem(pi);
        if rem.is_zero() {
            p = quot;
            mult += 1;
        } else {
            break;
        }
    }
    (mult, p)
}

// ───────────────────────── per-place local data ─────────────────────────

/// The residue field order `|κ| = q^{deg π}` (or `q` at the degree place).
///
/// One of the two base entry points that `debug_assert!` the [`FunctionFieldPlace::Finite`]
/// irreducibility precondition (release builds skip the check; the assumption is
/// still silently made, just unverified). The check runs only once a genuine `Some`
/// order is about to be returned — not before the `checked_pow` overflow guard —
/// since an overflow returns `None` regardless of whether `pi` is irreducible, and
/// that `None` is not a "meaningless success" the precondition needs to catch.
pub(crate) fn try_kappa_order<S: FiniteOddField>(place: &FunctionFieldPlace<S>) -> Option<u128> {
    let q = S::field_order();
    match place {
        FunctionFieldPlace::Finite(pi) => {
            let deg = pi
                .degree()
                .expect("an irreducible has degree ≥ 1")
                .try_into()
                .ok()?;
            let order = q.checked_pow(deg)?;
            debug_assert!(
                monic_irreducible_factors(pi) == vec![pi.clone()],
                "FunctionFieldPlace::Finite must carry a monic irreducible polynomial \
                 (q^deg(π) is a field order only when π is prime in F_q[t])"
            );
            Some(order)
        }
        FunctionFieldPlace::Infinite => Some(q),
    }
}

/// The valuation `v_place(a)` of a **nonzero** `a ∈ F_q(t)`.
///
/// The other base entry point (with `try_kappa_order`) that `debug_assert!`s the
/// [`FunctionFieldPlace::Finite`] irreducibility precondition: the `π`-adic
/// multiplicity below is only a discrete valuation when `π` is prime in `F_q[t]`.
pub fn try_valuation_at_ff<S: FiniteOddField>(
    a: &RationalFunction<S>,
    place: &FunctionFieldPlace<S>,
) -> Option<i128> {
    if a.is_zero() {
        return None;
    }
    Some(match place {
        FunctionFieldPlace::Finite(pi) => {
            debug_assert!(
                monic_irreducible_factors(pi) == vec![pi.clone()],
                "FunctionFieldPlace::Finite must carry a monic irreducible polynomial \
                 (the π-adic multiplicity is a discrete valuation only when π is prime in F_q[t])"
            );
            let (mn, _) = strip_factor(a.num().clone(), pi);
            let (md, _) = strip_factor(a.den().clone(), pi);
            mn - md
        }
        FunctionFieldPlace::Infinite => {
            let dn = a.num().degree().expect("nonzero numerator") as i128;
            let dd = a.den().degree().expect("monic nonzero denominator") as i128;
            dd - dn // v_∞ = deg(den) − deg(num)
        }
    })
}

/// The residue unit `(a / ϖ^{v(a)}) mod ϖ ∈ κ*` of a **nonzero** `a`, as an element
/// of the residue field: a [`Poly`] of degree `< deg π` at a finite place, or a
/// constant (an `F_q` element) at the degree place.
pub(crate) fn try_residue_unit_at<S: FiniteOddField>(
    a: &RationalFunction<S>,
    place: &FunctionFieldPlace<S>,
) -> Option<Poly<S>> {
    if a.is_zero() {
        return None;
    }
    match place {
        FunctionFieldPlace::Finite(pi) => {
            let (_, num_s) = strip_factor(a.num().clone(), pi);
            let (_, den_s) = strip_factor(a.den().clone(), pi);
            let num_mod = num_s.rem(pi);
            let den_mod = den_s.rem(pi);
            // den_mod⁻¹ in κ* by Fermat: x^{|κ|−2} (κ* is cyclic of order |κ|−1).
            let den_inv = den_mod.pow_mod(try_kappa_order(place)?.checked_sub(2)?, pi);
            Some(num_mod.mul_mod(&den_inv, pi))
        }
        FunctionFieldPlace::Infinite => {
            // a·t^{v_∞} → (lead num)/(lead den) as t → ∞.
            let ln = *a.num().leading().expect("nonzero numerator");
            let ld = *a.den().leading().expect("monic nonzero denominator");
            Some(Poly::constant(ln.mul(&ld.inv()?)))
        }
    }
}

/// The residue quadratic character `χ_κ(u) ∈ {+1, −1}` of a **nonzero** residue
/// unit `u ∈ κ*` — Euler's criterion `u^{(|κ|−1)/2}` in `F_q[t]/(π)` (or in `F_q`
/// at the degree place).
pub(crate) fn try_chi_kappa<S: FiniteOddField>(
    unit: &Poly<S>,
    place: &FunctionFieldPlace<S>,
) -> Option<i128> {
    match place {
        FunctionFieldPlace::Finite(pi) => {
            let e = (try_kappa_order(place)?.checked_sub(1)?) / 2;
            Some(if unit.pow_mod(e, pi) == Poly::one() {
                1
            } else {
                -1 // the unique order-2 element of κ* is −1
            })
        }
        FunctionFieldPlace::Infinite => Some(if is_square_finite::<S>(unit.coeff(0)) {
            1
        } else {
            -1
        }),
    }
}

/// Whether a **nonzero** `a` is a square in the local field at `place`: the
/// valuation is even **and** the residue unit is a square in `κ`. The mirror of
/// [`try_is_square_qp`](crate::forms::try_is_square_qp).
pub fn try_is_local_square_ff<S: FiniteOddField>(
    a: &RationalFunction<S>,
    place: &FunctionFieldPlace<S>,
) -> Option<bool> {
    if a.is_zero() {
        return Some(false);
    }
    Some(
        try_valuation_at_ff(a, place)?.rem_euclid(2) == 0
            && try_chi_kappa(&try_residue_unit_at(a, place)?, place)? == 1,
    )
}

// ───────────────────────── the Hilbert symbol ─────────────────────────

/// The Hilbert symbol `(a, b)_v` over the completion of `F_q(t)` at `place`, for
/// **nonzero** `a, b` — the **tame symbol**. With `α = v(a)`, `β = v(b)` and
/// residue units `ā, b̄`,
/// `(a,b)_v = χ_κ((−1)^{αβ}) · χ_κ(ā)^β · χ_κ(b̄)^α`,
/// exactly the odd-`p` branch of [`try_hilbert_symbol_qp`](crate::forms::try_hilbert_symbol_qp)
/// with the residue Legendre symbol replaced by the residue character `χ_κ`. No
/// `p = 2` branch exists because every residue field has odd characteristic.
pub fn try_hilbert_symbol_ff<S: FiniteOddField>(
    a: &RationalFunction<S>,
    b: &RationalFunction<S>,
    place: &FunctionFieldPlace<S>,
) -> Option<i128> {
    if a.is_zero() || b.is_zero() {
        return None;
    }
    let al = try_valuation_at_ff(a, place)?;
    let be = try_valuation_at_ff(b, place)?;
    let ca = try_chi_kappa(&try_residue_unit_at(a, place)?, place)?;
    let cb = try_chi_kappa(&try_residue_unit_at(b, place)?, place)?;
    // χ_κ(−1): −1 is a square in κ iff |κ| ≡ 1 (mod 4).
    let chi_neg1 = if try_kappa_order(place)? % 4 == 1 {
        1
    } else {
        -1
    };
    // Exactly the shared tame symbol — the same machine as the odd-`p` Q_p branch,
    // with the residue character `χ_κ` in place of the Legendre symbol.
    Some(crate::forms::tame_hilbert_symbol(al, be, ca, cb, chi_neg1))
}

// ───────────────────────── Hasse invariant + reciprocity ─────────────────────────

/// The relevant places of a list of **nonzero** entries: every finite place where
/// some entry has nonzero valuation (the monic irreducible factors of all
/// numerators and denominators), plus the degree place `∞`. At every other place
/// all entries are units, so every symbol is `+1`. Mirror of
/// [`relevant_primes`](crate::forms).
pub fn try_relevant_places_ff<S: FiniteOddField>(
    entries: &[RationalFunction<S>],
) -> Option<Vec<FunctionFieldPlace<S>>> {
    if entries.iter().any(|a| a.is_zero()) {
        return None;
    }
    let mut polys: Vec<Poly<S>> = Vec::new();
    for a in entries {
        let factors = monic_irreducible_factors(a.num())
            .into_iter()
            .chain(monic_irreducible_factors(a.den()));
        for pi in factors {
            if !polys.contains(&pi) {
                polys.push(pi);
            }
        }
    }
    let mut places: Vec<FunctionFieldPlace<S>> =
        polys.into_iter().map(FunctionFieldPlace::Finite).collect();
    places.push(FunctionFieldPlace::Infinite);
    Some(places)
}

/// The Hasse invariant `ε_v(⟨a_1,…,a_n⟩) = ∏_{i<j} (a_i, a_j)_v` at `place`. The
/// `_ff` suffix distinguishes it from the `ℚ` [`try_hasse_at_place`](crate::forms::try_hasse_at_place).
pub fn try_hasse_at_place_ff<S: FiniteOddField>(
    entries: &[RationalFunction<S>],
    place: &FunctionFieldPlace<S>,
) -> Option<i128> {
    let mut h = 1i128;
    for i in 0..entries.len() {
        for j in (i + 1)..entries.len() {
            h *= try_hilbert_symbol_ff(&entries[i], &entries[j], place)?;
        }
    }
    Some(h)
}

/// The **Hilbert reciprocity product** `∏_v (a,b)_v` over all places of `F_q(t)`,
/// `+1` for every nonzero `a, b` (Weil reciprocity / the product formula). Exact —
/// the symbols are `+1` at all but the finitely many relevant places.
pub fn try_hilbert_reciprocity_product_ff<S: FiniteOddField>(
    a: &RationalFunction<S>,
    b: &RationalFunction<S>,
) -> Option<i128> {
    <RationalFunction<S> as crate::forms::GlobalField>::try_reciprocity_product(a, b)
}

// ───────────────────────── Hasse–Minkowski over F_q(t) ─────────────────────────

/// `−1 ∈ F_q(t)`.
fn neg_one<S: FiniteOddField>() -> RationalFunction<S> {
    RationalFunction::from_base(S::one().neg())
}

/// The discriminant `∏ aᵢ ∈ F_q(t)` (its square class is the form's discriminant).
fn disc<S: FiniteOddField>(entries: &[RationalFunction<S>]) -> RationalFunction<S> {
    let mut d = RationalFunction::one();
    for e in entries {
        d = d.mul(e);
    }
    d
}

/// Whether a **nonzero** `x ∈ F_q(t)` is a global square. The square class of `x`
/// is represented by `num(x)·den(x) ∈ F_q[t]`, which is a square iff its `F_q`
/// leading coefficient is a square **and** every irreducible factor has even
/// multiplicity. The char-`p` analogue of `is_perfect_square` over `ℤ`.
pub(crate) fn is_global_square_ff<S: FiniteOddField>(x: &RationalFunction<S>) -> bool {
    if x.is_zero() {
        return false;
    }
    let f = x.num().mul(x.den());
    let lead = *f.leading().expect("nonzero square-class representative");
    if !is_square_finite::<S>(lead) {
        return false;
    }
    let mut g = f.make_monic();
    for pi in monic_irreducible_factors(&f) {
        let (mult, rest) = strip_factor(g, &pi);
        if mult.rem_euclid(2) != 0 {
            return false;
        }
        g = rest;
    }
    true
}

/// Local isotropy of a nondegenerate diagonal form `⟨a_1,…,a_n⟩` over the
/// completion of `F_q(t)` at `place`, by rank — the exact mirror of
/// [`try_is_isotropic_at_p`](crate::forms) (`F_q(t)` and `Q_p` share the
/// u-invariant `4`, so the thresholds match): `n≤1` never, `n=2` iff `−a_1a_2` is a
/// local square, `n=3`/`4` the Hilbert conditions, `n≥5` always. Entries nonzero.
pub fn try_is_isotropic_at_place_ff<S: FiniteOddField>(
    entries: &[RationalFunction<S>],
    place: &FunctionFieldPlace<S>,
) -> Option<bool> {
    if entries.iter().any(|a| a.is_zero()) {
        return Some(true);
    }
    Some(match entries.len() {
        0 | 1 => false,
        2 => try_is_local_square_ff(&entries[0].mul(&entries[1]).neg(), place)?,
        3 => {
            let d = disc(entries);
            try_hilbert_symbol_ff(&neg_one(), &d.neg(), place)?
                == try_hasse_at_place_ff(entries, place)?
        }
        4 => {
            let d = disc(entries);
            !try_is_local_square_ff(&d, place)?
                || try_hasse_at_place_ff(entries, place)?
                    == try_hilbert_symbol_ff(&neg_one::<S>(), &neg_one::<S>(), place)?
        }
        _ => true,
    })
}

/// Whether a diagonal form over `F_q(t)` is **isotropic**, by **Hasse–Minkowski**:
/// isotropic over the global field iff isotropic at every place. Unlike `ℚ` there
/// is **no archimedean place**, so rank ≥ 3 needs only the local conditions at the
/// relevant places (all other places are unit forms, automatically isotropic for
/// rank ≥ 3 over a finite residue field). Rank 2 reduces to `−a_1a_2` being a
/// global square; a zero entry is an isotropic direction.
pub fn try_is_isotropic_ff<S: FiniteOddField>(entries: &[RationalFunction<S>]) -> Option<bool> {
    <RationalFunction<S> as crate::forms::GlobalField>::try_is_isotropic_global(entries)
}

/// The per-place isotropy breakdown of a rank-`≥3` form — the function-field
/// analogue of [`AdelicIsotropy`](crate::forms::AdelicIsotropy) (no real place).
#[derive(Debug, Clone)]
pub struct FFAdelicIsotropy<S: FiniteOddField> {
    /// `(place, is_isotropic_there)` at each relevant place.
    pub local: Vec<(FunctionFieldPlace<S>, bool)>,
}

impl<S: FiniteOddField> FFAdelicIsotropy<S> {
    /// Globally isotropic ⟺ isotropic at every place (Hasse–Minkowski).
    pub fn is_global(&self) -> bool {
        self.local.iter().all(|(_, iso)| *iso)
    }

    /// `display()` alias kept for Python callers.
    pub fn display(&self) -> String {
        self.to_string()
    }
}

impl<S: FiniteOddField> std::fmt::Display for FFAdelicIsotropy<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "FFAdelicIsotropy(local=[")?;
        for (i, (place, iso)) in self.local.iter().enumerate() {
            if i > 0 {
                write!(f, ", ")?;
            }
            write!(f, "{place}={iso}")?;
        }
        write!(f, "], is_global={})", self.is_global())
    }
}

/// The adelic Hasse–Minkowski breakdown of a rank-`≥3` form over `F_q(t)`.
pub fn try_isotropy_over_ff_adeles<S: FiniteOddField>(
    entries: &[RationalFunction<S>],
) -> Option<FFAdelicIsotropy<S>> {
    if entries.iter().any(|a| a.is_zero()) {
        return Some(FFAdelicIsotropy { local: Vec::new() });
    }
    let mut local = Vec::new();
    for pl in try_relevant_places_ff(entries)? {
        let iso = try_is_isotropic_at_place_ff(entries, &pl)?;
        local.push((pl, iso));
    }
    Some(FFAdelicIsotropy { local })
}

/// The places where the quaternion algebra `(a, b)` over `F_q(t)` **ramifies** —
/// where `(a,b)_v = −1`. The count is always **even** (the additive form of
/// reciprocity / the even-ramification theorem), the function-field mirror of
/// [`brauer_local_invariants`](crate::forms::brauer_local_invariants).
pub fn try_ramified_places_ff<S: FiniteOddField>(
    a: &RationalFunction<S>,
    b: &RationalFunction<S>,
) -> Option<Vec<FunctionFieldPlace<S>>> {
    <RationalFunction<S> as crate::forms::GlobalField>::try_ramified_places(a, b)
}

// ───────────────────── Bridge K: the constant-extension cyclic class ─────────────────────

/// The canonical representative in `[0, 1)` of `m/n` mod `ℤ` (`n > 0`).
fn frac_mod_one_ratio(m: i128, n: i128) -> Option<Rational> {
    Rational::try_new(m.rem_euclid(n), n)
}

fn finite_order<S: FiniteOddField>(x: S) -> Option<u128> {
    if x.is_zero() {
        return None;
    }
    let group = S::field_order().checked_sub(1)?;
    let mut cur = S::one();
    for k in 1..=group {
        cur = cur.mul(&x);
        if cur == S::one() {
            return Some(k);
        }
    }
    None
}

fn constant_field_primitive<S: FiniteOddField>() -> Option<S> {
    let group = S::field_order().checked_sub(1)?;
    for i in 1..S::field_order() {
        let g = S::from_index(i);
        if finite_order(g) == Some(group) {
            return Some(g);
        }
    }
    None
}

fn kappa_mul<S: FiniteOddField>(
    a: &Poly<S>,
    b: &Poly<S>,
    place: &FunctionFieldPlace<S>,
) -> Poly<S> {
    match place {
        FunctionFieldPlace::Finite(pi) => a.mul_mod(b, pi),
        FunctionFieldPlace::Infinite => Poly::constant(a.coeff(0).mul(&b.coeff(0))),
    }
}

fn kappa_pow<S: FiniteOddField>(
    base: &Poly<S>,
    mut e: u128,
    place: &FunctionFieldPlace<S>,
) -> Poly<S> {
    let mut acc = Poly::one();
    let mut b = base.clone();
    while e > 0 {
        if e & 1 == 1 {
            acc = kappa_mul(&acc, &b, place);
        }
        e >>= 1;
        if e > 0 {
            b = kappa_mul(&b, &b, place);
        }
    }
    acc
}

fn kappa_pow_signed<S: FiniteOddField>(
    base: &Poly<S>,
    e: i128,
    place: &FunctionFieldPlace<S>,
) -> Option<Poly<S>> {
    if e >= 0 {
        Some(kappa_pow(base, e as u128, place))
    } else {
        let inv = kappa_pow(base, try_kappa_order(place)?.checked_sub(2)?, place);
        Some(kappa_pow(&inv, e.unsigned_abs(), place))
    }
}

fn tame_symbol_raw_ff<S: FiniteOddField>(
    a: &RationalFunction<S>,
    b: &RationalFunction<S>,
    place: &FunctionFieldPlace<S>,
) -> Option<Poly<S>> {
    if a.is_zero() || b.is_zero() {
        return None;
    }
    let alpha = try_valuation_at_ff(a, place)?;
    let beta = try_valuation_at_ff(b, place)?;
    let mut raw = if alpha.rem_euclid(2) == 1 && beta.rem_euclid(2) == 1 {
        Poly::constant(S::one().neg())
    } else {
        Poly::one()
    };
    raw = kappa_mul(
        &raw,
        &kappa_pow_signed(&try_residue_unit_at(a, place)?, beta, place)?,
        place,
    );
    raw = kappa_mul(
        &raw,
        &kappa_pow_signed(&try_residue_unit_at(b, place)?, -alpha, place)?,
        place,
    );
    Some(raw)
}

fn kappa_log_with_order<S: FiniteOddField>(
    base: &Poly<S>,
    x: &Poly<S>,
    order: u128,
    place: &FunctionFieldPlace<S>,
) -> Option<u128> {
    let mut cur = Poly::one();
    for e in 0..order {
        if cur == *x {
            return Some(e);
        }
        cur = kappa_mul(&cur, base, place);
    }
    None
}

/// The exponent `e ∈ {0, …, n−1}` of the tame Kummer symbol `(a,b)_v = ζ_n^e`
/// over the completion of `F_q(t)` at `place`. The primitive root `ζ_n` is chosen
/// in the **constant field** `F_q` (the first primitive generator of `F_q*`, raised
/// to `(q−1)/n`) and then embedded into each residue field, so exponents at
/// different places share one reciprocity convention.
///
/// Returns `None` when `a` or `b` is zero, `n = 0`, or `n ∤ q−1`; the last condition
/// is the tame Kummer boundary `μ_n ⊂ F_q`.
pub fn try_tame_symbol_exponent_ff<S: FiniteOddField>(
    n: u128,
    a: &RationalFunction<S>,
    b: &RationalFunction<S>,
    place: &FunctionFieldPlace<S>,
) -> Option<u128> {
    if n == 0 {
        return None;
    }
    let constant_group = S::field_order().checked_sub(1)?;
    if constant_group % n != 0 {
        return None;
    }
    if n == 1 {
        return Some(0);
    }
    let raw = tame_symbol_raw_ff(a, b, place)?;
    let residue_group = try_kappa_order(place)?.checked_sub(1)?;
    let value = kappa_pow(&raw, residue_group.checked_div(n)?, place);
    let zeta = constant_field_primitive::<S>()?.pow(constant_group.checked_div(n)?);
    kappa_log_with_order(&Poly::constant(zeta), &value, n, place)
}

/// The local invariant `e/n ∈ ℚ/ℤ` attached to
/// [`try_tame_symbol_exponent_ff`], reduced to `[0,1)`.
pub fn try_tame_symbol_invariant_ff<S: FiniteOddField>(
    n: u128,
    a: &RationalFunction<S>,
    b: &RationalFunction<S>,
    place: &FunctionFieldPlace<S>,
) -> Option<Rational> {
    let e = i128::try_from(try_tame_symbol_exponent_ff(n, a, b, place)?).ok()?;
    let ni = i128::try_from(n).ok()?;
    frac_mod_one_ratio(e, ni)
}

/// The nonzero tame-symbol local invariants of the Kummer cyclic class over
/// `F_q(t)`, for `μ_n ⊂ F_q`. This is the ramified tame counterpart to
/// [`constant_extension_invariants`]: it uses the tame symbol at zeros and poles of
/// `a` and `b`, and leaves the wild case out.
pub fn tame_symbol_invariants_ff<S: FiniteOddField>(
    n: u128,
    a: &RationalFunction<S>,
    b: &RationalFunction<S>,
) -> Option<Vec<(FunctionFieldPlace<S>, Rational)>> {
    if a.is_zero() || b.is_zero() || n == 0 {
        return None;
    }
    if S::field_order().checked_sub(1)? % n != 0 {
        return None;
    }
    let mut out = Vec::new();
    for place in try_relevant_places_ff(&[a.clone(), b.clone()])? {
        let inv = try_tame_symbol_invariant_ff(n, a, b, &place)?;
        if !inv.is_zero() {
            out.push((place, inv));
        }
    }
    Some(out)
}

/// The reciprocity sum `∑_v inv_v` mod `ℤ` of the tame Kummer symbol over
/// `F_q(t)`. With the constant-field `ζ_n` convention used by
/// [`try_tame_symbol_exponent_ff`], this is `0` for nonzero `a,b` whenever
/// `μ_n ⊂ F_q`.
pub fn tame_symbol_invariant_sum_ff<S: FiniteOddField>(
    n: u128,
    a: &RationalFunction<S>,
    b: &RationalFunction<S>,
) -> Option<Rational> {
    let invs = tame_symbol_invariants_ff(n, a, b)?;
    let sum = invs
        .into_iter()
        .fold(Rational::from_int(0), |acc, (_, inv)| acc.add(&inv));
    frac_mod_one_ratio(sum.numer(), sum.denom())
}

/// The local invariants `inv_v = deg(v)·v(a)/n (mod ℤ)` of the **constant-extension**
/// cyclic algebra `(χ_σ, a)` over `K = F_q(t)`, where `E = F_{qⁿ}(t)` is the degree-`n`
/// constant extension and `σ` is the `q`-power Frobenius. This is Bridge K at full
/// **`ℚ/ℤ` strength** over a global field — and the function-field route is the *clean*
/// one: a constant extension is **unramified at every place** (including `∞`), with
/// `Frob_v = σ^{deg v}`, so the general local symbol collapses to the formula above and
/// no ramified symbols are ever needed. (Over `ℚ`, by Minkowski every cyclic extension
/// of degree `> 1` ramifies somewhere, so the `n > 2` story needs ramified symbols —
/// out of this bridge's scope; here it falls out for free.)
///
/// Returns `(place, inv_v)` at each relevant place with nonzero invariant, mirroring
/// the shape of [`brauer_local_invariants`](crate::forms::brauer_local_invariants)
/// (a `Vec`, since [`FunctionFieldPlace`] is not `Ord`). Exact: only `deg(v)`, `v(a)`, and `n`
/// are read. `None` if `a = 0` (not in `K*`), `n = 0`, or arithmetic overflows.
///
/// The reciprocity law `∑_v inv_v ≡ 0` ([`constant_extension_invariant_sum`]) is then
/// `deg(div a)/n = 0` — the product formula the function-field layer already embodies.
pub fn constant_extension_invariants<S: FiniteOddField>(
    n: u128,
    a: &RationalFunction<S>,
) -> Option<Vec<(FunctionFieldPlace<S>, Rational)>> {
    if a.is_zero() || n == 0 {
        return None;
    }
    let ni = i128::try_from(n).ok()?;
    let mut out = Vec::new();
    for place in try_relevant_places_ff(std::slice::from_ref(a))? {
        let v = try_valuation_at_ff(a, &place)?;
        let deg = match &place {
            FunctionFieldPlace::Finite(pi) => i128::try_from(pi.degree()?).ok()?,
            FunctionFieldPlace::Infinite => 1,
        };
        let inv = frac_mod_one_ratio(deg.checked_mul(v)?, ni)?;
        if !inv.is_zero() {
            out.push((place, inv));
        }
    }
    Some(out)
}

/// The reciprocity sum `∑_v inv_v` mod `ℤ` of the constant-extension class — `0` for
/// every nonzero `a` (full-`ℚ/ℤ`-strength Albert–Brauer–Hasse–Noether reciprocity over
/// `F_q(t)`, equal to `deg(div a)/n = 0`). The function-field mirror of
/// [`brauer_invariant_sum`](crate::forms::brauer_invariant_sum).
pub fn constant_extension_invariant_sum<S: FiniteOddField>(
    n: u128,
    a: &RationalFunction<S>,
) -> Option<Rational> {
    let invs = constant_extension_invariants(n, a)?;
    let sum = invs
        .into_iter()
        .fold(Rational::from_int(0), |acc, (_, inv)| acc.add(&inv));
    frac_mod_one_ratio(sum.numer(), sum.denom())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::scalar::Fp;

    type F = RationalFunction<Fp<5>>;
    type PolyF = Poly<Fp<5>>;

    fn rf(num: &[i128], den: &[i128]) -> F {
        RationalFunction::new(
            num.iter().map(|&n| Fp::<5>::from_int(n)).collect(),
            den.iter().map(|&n| Fp::<5>::from_int(n)).collect(),
        )
    }
    fn poly(c: &[i128]) -> PolyF {
        Poly::new(c.iter().map(|&n| Fp::<5>::from_int(n)).collect())
    }

    // --- Display: exact-string render pins ---

    #[test]
    fn function_field_place_display_render_pin() {
        assert_eq!(
            FunctionFieldPlace::<Fp<5>>::Finite(poly(&[0, 1])).to_string(),
            "t"
        );
        assert_eq!(
            FunctionFieldPlace::<Fp<5>>::Finite(poly(&[1, 1])).to_string(),
            "t + 1"
        );
        assert_eq!(FunctionFieldPlace::<Fp<5>>::Infinite.to_string(), "");
    }

    #[test]
    fn ff_adelic_isotropy_display_render_pin() {
        let iso = FFAdelicIsotropy::<Fp<5>> {
            local: vec![
                (FunctionFieldPlace::Finite(poly(&[0, 1])), true),
                (FunctionFieldPlace::Infinite, false),
            ],
        };
        assert_eq!(
            iso.to_string(),
            "FFAdelicIsotropy(local=[t=true, ∞=false], is_global=false)"
        );
        assert_eq!(iso.display(), iso.to_string());
    }

    #[test]
    fn factors_into_monic_irreducibles() {
        // x² − 1 = (x − 1)(x + 1) over F_5  (constant −1 ≡ 4)
        let fs = monic_irreducible_factors(&poly(&[4, 0, 1]));
        assert_eq!(fs.len(), 2);
        assert!(fs.contains(&poly(&[4, 1]))); // x − 1
        assert!(fs.contains(&poly(&[1, 1]))); // x + 1
                                              // x² + 2 is irreducible over F_5 (−2 ≡ 3 is a nonsquare): one factor, itself.
        let irr = monic_irreducible_factors(&poly(&[2, 0, 1]));
        assert_eq!(irr, vec![poly(&[2, 0, 1])]);
        // a repeated factor is reported once (square-free support).
        let sq = monic_irreducible_factors(&poly(&[1, 2, 1])); // (x+1)²
        assert_eq!(sq, vec![poly(&[1, 1])]);
    }

    #[test]
    #[should_panic(expected = "monic irreducible polynomial")]
    fn finite_place_precondition_rejects_reducible_polynomial() {
        // x² − 1 = (x−1)(x+1) over F_5 is reducible: the FunctionFieldPlace::Finite
        // precondition is violated, and try_kappa_order's debug_assert catches it
        // (this test only exercises the debug/test build path, by design).
        let reducible = FunctionFieldPlace::<Fp<5>>::Finite(poly(&[4, 0, 1]));
        let _ = try_kappa_order(&reducible);
    }

    #[test]
    fn valuations_at_places() {
        // a = t / (t + 1)
        let a = rf(&[0, 1], &[1, 1]);
        assert_eq!(
            try_valuation_at_ff(&a, &FunctionFieldPlace::Finite(poly(&[0, 1]))),
            Some(1)
        ); // at π = t
        assert_eq!(
            try_valuation_at_ff(&a, &FunctionFieldPlace::Finite(poly(&[1, 1]))),
            Some(-1)
        ); // at π = t+1
        assert_eq!(
            try_valuation_at_ff(&a, &FunctionFieldPlace::Infinite),
            Some(0)
        ); // deg den − deg num = 0
           // 1/t² has a double pole at ∞? no: v_∞(1/t²) = deg(t²) − deg(1) = 2.
        assert_eq!(
            try_valuation_at_ff(&rf(&[1], &[0, 0, 1]), &FunctionFieldPlace::Infinite),
            Some(2)
        );
    }

    #[test]
    fn residue_field_order_overflow_returns_none() {
        let pi = Poly::<Fp<5>>::monomial(56, Fp::<5>::one()).add(&Poly::one());
        assert_eq!(try_kappa_order(&FunctionFieldPlace::Finite(pi)), None);
    }

    #[test]
    fn hilbert_symbol_is_symmetric_and_steinberg() {
        let samples = [
            rf(&[0, 1], &[1]),
            rf(&[2], &[1]),
            rf(&[1, 1], &[1]),
            rf(&[0, 1], &[1, 1]),
        ];
        let places = [
            FunctionFieldPlace::Infinite,
            FunctionFieldPlace::Finite(poly(&[0, 1])), // t
            FunctionFieldPlace::Finite(poly(&[1, 1])), // t+1
            FunctionFieldPlace::Finite(poly(&[2, 0, 1])), // t²+2 (degree-2 place, residue F_25)
        ];
        for a in &samples {
            for b in &samples {
                for pl in &places {
                    assert_eq!(
                        try_hilbert_symbol_ff(a, b, pl),
                        try_hilbert_symbol_ff(b, a, pl),
                        "symmetry"
                    );
                }
                // Steinberg: (a, −a)_v = 1.
                let neg_a = a.mul(&F::from_base(Fp::<5>::from_int(-1)));
                for pl in &places {
                    assert_eq!(
                        try_hilbert_symbol_ff(a, &neg_a, pl),
                        Some(1),
                        "(a,−a)_v = 1"
                    );
                }
            }
        }
    }

    #[test]
    fn reciprocity_holds_small() {
        // ∏_v (a,b)_v = +1 — the gold oracle, exact over F_q(t).
        let samples = [
            rf(&[0, 1], &[1]),    // t
            rf(&[1, 1], &[1]),    // t+1
            rf(&[2], &[1]),       // the nonsquare constant 2
            rf(&[0, 1], &[1, 1]), // t/(t+1)
            rf(&[2, 0, 1], &[1]), // t²+2 (irreducible)
        ];
        for a in &samples {
            for b in &samples {
                assert_eq!(
                    try_hilbert_reciprocity_product_ff(a, b),
                    Some(1),
                    "reciprocity failed at a={a:?} b={b:?}"
                );
            }
        }
    }

    #[test]
    fn quaternion_ramifies_at_an_even_number_of_places() {
        // The function-field mirror of "Hamilton's quaternions ramify at 2 and ∞":
        // (t, 2) over F_5(t) — with 2 a nonsquare constant — ramifies at exactly the
        // linear place π = t and the degree place ∞ (an even set, as reciprocity
        // forces).
        let a = rf(&[0, 1], &[1]); // t
        let b = rf(&[2], &[1]); // the nonsquare 2
        let ram = try_ramified_places_ff(&a, &b).unwrap();
        assert_eq!(ram.len(), 2, "even number of ramified places");
        assert!(ram.contains(&FunctionFieldPlace::Finite(poly(&[0, 1])))); // π = t
        assert!(ram.contains(&FunctionFieldPlace::Infinite)); //                                                              // a split quaternion (a square second slot) ramifies nowhere.
        assert!(try_ramified_places_ff(&a, &rf(&[4], &[1]))
            .unwrap()
            .is_empty()); // 4 = 2² is a square
    }

    #[test]
    fn hasse_minkowski_global_matches_adelic() {
        // For rank ≥ 3, try_is_isotropic_ff agrees with the per-place adelic breakdown.
        let forms: [Vec<F>; 4] = [
            vec![rf(&[1], &[1]), rf(&[1], &[1]), rf(&[4], &[1])], // ⟨1,1,−1⟩ isotropic
            vec![rf(&[1], &[1]), rf(&[0, 1], &[1]), rf(&[0, 4], &[1])], // ⟨1,t,−t⟩ isotropic
            // ⟨1,−t,−2,2t⟩ = norm form of the division quaternion (t,2): anisotropic
            vec![
                rf(&[1], &[1]),
                rf(&[0, 4], &[1]),
                rf(&[3], &[1]),
                rf(&[0, 2], &[1]),
            ],
            // …extend by ⟨…,1⟩ to rank 5: u-invariant 4 ⇒ isotropic
            vec![
                rf(&[1], &[1]),
                rf(&[0, 4], &[1]),
                rf(&[3], &[1]),
                rf(&[0, 2], &[1]),
                rf(&[1], &[1]),
            ],
        ];
        let expected = [true, true, false, true];
        for (form, &exp) in forms.iter().zip(&expected) {
            assert_eq!(
                try_is_isotropic_ff(form),
                Some(exp),
                "global isotropy of {form:?}"
            );
            assert_eq!(
                try_isotropy_over_ff_adeles(form).unwrap().is_global(),
                exp,
                "adelic isotropy of {form:?}"
            );
        }
    }

    #[test]
    fn cross_checks_springer_laurent_at_a_linear_place() {
        // Independent-oracle check: at a linear place π = t − 1 (residue field F_5),
        // the F_q(t) place layer must read the same valuation/discriminant data as
        // the established Laurent Springer decomposition. Entries are expanded at
        // t = 1 by hand for the Laurent side and kept as polynomials for the F_q(t)
        // side; the two code paths are completely independent.
        use crate::clifford::Metric;
        use crate::forms::springer_decompose_laurent;
        use crate::scalar::Laurent;
        type L5 = Laurent<Fp<5>, 4>;
        let lc = |cs: &[i128], v: i128| {
            L5::from_coeffs(cs.iter().map(|&n| Fp::<5>::from_int(n)).collect(), v)
        };

        let pi = poly(&[4, 1]); // t − 1 over F_5
        let place = FunctionFieldPlace::Finite(pi.clone());

        // ⟨ 2,  t−1,  t²+1 ⟩  — valuations 0,1,0 at π; residues 2 (nonsq), 1, 2.
        let ff = [
            rf(&[2], &[1]),       // 2
            rf(&[4, 1], &[1]),    // t − 1
            rf(&[1, 0, 1], &[1]), // t² + 1
        ];
        // the same form localized at s = t − 1: 2 = 2·s⁰; t−1 = s¹; t²+1 = s²+2s+2.
        let laurent = Metric::diagonal(vec![lc(&[2], 0), lc(&[1], 1), lc(&[2, 2, 1], 0)]);
        let decomp = springer_decompose_laurent(&laurent).unwrap();

        for layer in &decomp.graded {
            let at: Vec<&F> = ff
                .iter()
                .filter(|e| try_valuation_at_ff(e, &place) == Some(layer.valuation))
                .collect();
            assert_eq!(at.len(), layer.dim, "dim at valuation {}", layer.valuation);
            // discriminant square class = XNOR of the per-entry residue characters.
            let disc_sq = at.iter().fold(true, |acc, e| {
                acc == (try_chi_kappa(&try_residue_unit_at(e, &place).unwrap(), &place) == Some(1))
            });
            assert_eq!(
                disc_sq, layer.disc_is_square,
                "disc class at valuation {}",
                layer.valuation
            );
        }
    }

    #[test]
    fn tame_symbol_quadratic_slice_matches_hilbert_symbol() {
        let samples = [
            rf(&[0, 1], &[1]),    // t
            rf(&[2], &[1]),       // nonsquare constant
            rf(&[1, 1], &[1]),    // t+1
            rf(&[0, 1], &[1, 1]), // t/(t+1)
        ];
        let places = [
            FunctionFieldPlace::Infinite,
            FunctionFieldPlace::Finite(poly(&[0, 1])),
            FunctionFieldPlace::Finite(poly(&[1, 1])),
            FunctionFieldPlace::Finite(poly(&[2, 0, 1])),
        ];
        for a in &samples {
            for b in &samples {
                for place in &places {
                    let exp = try_tame_symbol_exponent_ff(2, a, b, place).unwrap();
                    let hilb = try_hilbert_symbol_ff(a, b, place).unwrap();
                    assert_eq!(
                        exp,
                        if hilb == 1 { 0 } else { 1 },
                        "quadratic tame slice at {place:?}"
                    );
                }
            }
        }
    }

    #[test]
    fn tame_symbol_degree_four_convention_and_reciprocity() {
        let t = rf(&[0, 1], &[1]);
        let two = rf(&[2], &[1]); // first primitive generator of F_5*
        let at_t = FunctionFieldPlace::Finite(poly(&[0, 1]));

        assert_eq!(try_tame_symbol_exponent_ff(4, &two, &t, &at_t), Some(1));
        assert_eq!(
            try_tame_symbol_invariant_ff(4, &two, &t, &at_t),
            Some(Rational::try_new(1, 4).unwrap())
        );
        assert_eq!(
            try_tame_symbol_exponent_ff(4, &t, &two, &at_t),
            Some(3),
            "a^v(b)/b^v(a) makes the swapped symbol inverse"
        );
        assert_eq!(
            try_tame_symbol_invariant_ff(4, &t, &two, &at_t),
            Some(Rational::try_new(3, 4).unwrap())
        );

        let invs = tame_symbol_invariants_ff(4, &t, &two).unwrap();
        assert_eq!(invs.len(), 2, "finite t-place plus infinity");
        assert!(invs.contains(&(
            FunctionFieldPlace::Finite(poly(&[0, 1])),
            Rational::try_new(3, 4).unwrap()
        )));
        assert!(invs.contains(&(
            FunctionFieldPlace::Infinite,
            Rational::try_new(1, 4).unwrap()
        )));
        assert_eq!(
            tame_symbol_invariant_sum_ff(4, &t, &two),
            Some(Rational::zero())
        );
        assert_eq!(
            tame_symbol_invariants_ff(3, &t, &two),
            None,
            "3 is tame at some residue extensions but μ_3 is not in F_5"
        );
        assert_eq!(tame_symbol_invariants_ff(4, &F::zero(), &two), None);
    }

    #[test]
    fn constant_extension_reciprocity_full_strength() {
        // Bridge K at full ℚ/ℤ strength: Σ_v deg(v)·v(a)/n ≡ 0 for constant extensions
        // of *any* degree n (not only the 2-torsion ½-slice) — reduced to deg(div a)=0,
        // with no ramified symbols (every place is unramified in a constant extension).
        let samples = [
            rf(&[0, 1], &[1]),       // t
            rf(&[1, 1], &[1]),       // t+1
            rf(&[0, 1], &[1, 1]),    // t/(t+1)
            rf(&[2, 0, 1], &[1]),    // t²+2 (irreducible, a degree-2 place)
            rf(&[0, 0, 1], &[2, 1]), // t²/(t+2)
        ];
        for n in [2u128, 3, 4, 5] {
            for a in &samples {
                assert_eq!(
                    constant_extension_invariant_sum(n, a),
                    Some(Rational::from_int(0)),
                    "reciprocity n={n} a={a:?}"
                );
                // independent oracle: the divisor degree Σ deg(v)·v(a) = 0.
                let mut div_deg = 0i128;
                for place in try_relevant_places_ff(std::slice::from_ref(a)).unwrap() {
                    let v = try_valuation_at_ff(a, &place).unwrap();
                    let deg = match &place {
                        FunctionFieldPlace::Finite(pi) => pi.degree().unwrap() as i128,
                        FunctionFieldPlace::Infinite => 1,
                    };
                    div_deg += deg * v;
                }
                assert_eq!(div_deg, 0, "deg(div a)=0 for a={a:?}");
            }
        }
    }

    #[test]
    fn constant_extension_image_is_full_and_good_places_split() {
        // a unit (nonzero constant) is unramified everywhere ⇒ empty invariant map.
        assert_eq!(
            constant_extension_invariants(3, &rf(&[2], &[1])),
            Some(vec![])
        );
        // the image hits the full (1/n)ℤ/ℤ: at π = t (v=1, deg=1), inv = 1/3 for n=3.
        let invs = constant_extension_invariants(3, &rf(&[0, 1], &[1])).unwrap();
        let at_t = invs
            .iter()
            .find(|(pl, _)| *pl == FunctionFieldPlace::Finite(poly(&[0, 1])))
            .map(|(_, r)| r.clone());
        assert_eq!(at_t, Some(Rational::try_new(1, 3).unwrap()));
        // a degree-2 place carries deg(v)=2: at π = t²+2 (v=1), inv = 2/3 for n=3 —
        // a value invisible to the 2-torsion Bridge F surface.
        let invs_b = constant_extension_invariants(3, &rf(&[2, 0, 1], &[1])).unwrap();
        let at_b = invs_b
            .iter()
            .find(|(pl, _)| *pl == FunctionFieldPlace::Finite(poly(&[2, 0, 1])))
            .map(|(_, r)| r.clone());
        assert_eq!(at_b, Some(Rational::try_new(2, 3).unwrap()));
        // n=1 (trivial extension, split Brauer): everything splits.
        assert_eq!(
            constant_extension_invariants(1, &rf(&[0, 1], &[1])),
            Some(vec![])
        );
        // degenerate inputs rejected.
        assert_eq!(constant_extension_invariants(0, &rf(&[0, 1], &[1])), None);
        assert_eq!(constant_extension_invariants(3, &rf(&[0], &[1])), None);
    }

    #[test]
    fn rank_two_is_a_global_square_condition() {
        // ⟨1, −t²⟩: −(1·−t²) = t² is a global square ⇒ isotropic.
        assert_eq!(
            try_is_isotropic_ff(&[rf(&[1], &[1]), rf(&[0, 0, 4], &[1])]),
            Some(true)
        );
        // ⟨1, −t⟩: −(1·−t) = t has an odd-multiplicity place ⇒ not a square ⇒ anisotropic.
        assert_eq!(
            try_is_isotropic_ff(&[rf(&[1], &[1]), rf(&[0, 4], &[1])]),
            Some(false)
        );
        // ⟨1, −2⟩: −(−2) = 2 is a nonsquare constant ⇒ anisotropic.
        assert_eq!(
            try_is_isotropic_ff(&[rf(&[1], &[1]), rf(&[3], &[1])]),
            Some(false)
        );
        // ⟨2, −8⟩: −(2·−8) = 16 = 4² is a square ⇒ isotropic.
        assert_eq!(
            try_is_isotropic_ff(&[rf(&[2], &[1]), rf(&[2], &[1])]),
            Some(true)
        ); // 2 and 2: −(4)=−4≡1=1²
    }
}