"""Phase 4 validation: fermion sector (SM leptons, SVD/Takagi, seesaw).

Pinned physics:
- h ℓℓ Yukawa vertex = −i m_ℓ / v   (with Y_ℓ = √2 m_ℓ / v)
- W⁺ ν̄ℓ current    = i g/√2 γ^μ P_L
- Z ℓ̄ℓ current: coefficient ∝ (T³ − Q sin²θ_W) pattern
- photon coupling of the charged lepton = −e (electric charge)
- toy seesaw: Takagi of [[0, m_D], [m_D, M_R]] reproduces the seesaw light
  mass at leading order (cross-check with verify.seesaw_light_mass)
"""

import sympy as sp
import pytest

from feynlag import (
    Bilinear, DiracGamma, ExternalParameter, Rotation, SU2, Scalar, U1,
    Vacuum, WeylFermion, diagonalize_svd, diagonalize_svd_2x2,
    diagonalize_takagi, diracPL, diracPR, extract_fermion_vertices,
    fermion_feynman_rule, fermion_gauge_current, fermion_mass_matrix,
    numeric_equal, rotation_2x2, seesaw_light_mass,
)

i, j = sp.symbols("fl_i fl_j", integer=True)


@pytest.fixture(scope="module")
def sm_leptons():
    gw = ExternalParameter("gw", 0.6535, positive=True)
    g1 = ExternalParameter("g1", 0.3580, positive=True)
    SU2L, U1Y = SU2("SU2L", coupling=gw), U1("U1Y", coupling=g1)

    v = ExternalParameter("v", 246.0, positive=True, unit_dim=1)
    H = Scalar("H", reps={SU2L: 2, U1Y: sp.Rational(1, 2)},
               component_names=["Gp", "H0"])
    H.expand_vev({H.components[1]: v})

    Ll = WeylFermion("Ll", reps={SU2L: 2, U1Y: -sp.Rational(1, 2)},
                     chirality="L", nflavors=3,
                     component_names=["nuL", "eL"])
    eR = WeylFermion("eR", reps={U1Y: -1}, chirality="R", nflavors=3,
                     component_names=["eR"])
    return SU2L, U1Y, H, Ll, eR, v, gw, g1


class TestYukawa:
    def _yukawa(self, sm_leptons):
        """L_Yuk = − Y[i,j] L̄_i H e_R[j] + h.c. in components."""
        SU2L, U1Y, H, Ll, eR, v, gw, g1 = sm_leptons
        Y = sp.IndexedBase("Ye")
        nuLbar, eLbar = Ll.bar_components
        Gp, H0 = H.components
        # ψ̄_L (…) χ_R sandwiches carry P_R
        LYuk = -(Y[i, j] * Gp * Bilinear(nuLbar[i], diracPR, eR.components[0][j])
                 + Y[i, j] * H0 * Bilinear(eLbar[i], diracPR, eR.components[0][j]))
        # + h.c. (χ̄_R (…) ψ_L carries P_L, conjugated coupling/scalars)
        eRbar = eR.bar_components[0]
        LYuk += -(sp.conjugate(Y[i, j]) * sp.conjugate(Gp)
                  * Bilinear(eRbar[j], diracPL, Ll.components[0][i])
                  + sp.conjugate(Y[i, j]) * sp.conjugate(H0)
                  * Bilinear(eRbar[j], diracPL, Ll.components[1][i]))
        return LYuk, Y

    def test_mass_matrix(self, sm_leptons):
        SU2L, U1Y, H, Ll, eR, v, gw, g1 = sm_leptons
        LYuk, Y = self._yukawa(sm_leptons)
        vac = Vacuum([H])
        eLbar = Ll.bar_components[1]
        M = fermion_mass_matrix(LYuk, eLbar, eR.components[0], vac, 3, (i, j),
                                gamma=diracPR)
        # M[a,b] = Y[a,b] v / sqrt(2)
        for a in range(3):
            for b in range(3):
                assert sp.simplify(M[a, b] - Y[a, b] * v.s / sp.sqrt(2)) == 0

    def test_hll_coupling_pinned(self, sm_leptons):
        """With diagonal Y = √2 m_ℓ/v: h ℓℓ vertex = −i m_ℓ/v P_R (+ h.c.)."""
        SU2L, U1Y, H, Ll, eR, v, gw, g1 = sm_leptons
        LYuk, Y = self._yukawa(sm_leptons)
        vac = Vacuum([H])

        # physical basis: expand H0 around the vacuum
        L_shifted = sp.expand(LYuk.xreplace(vac.shift_map))
        h = sp.Symbol("H0_r", real=True)
        table = extract_fermion_vertices(L_shifted, [h])

        eLbar = Ll.bar_components[1]
        key = (eLbar[i], diracPR, eR.components[0][j])
        coeff_h = table[key][1][(h,)]
        assert sp.simplify(coeff_h + Y[i, j] / sp.sqrt(2)) == 0

        # rule with m_ell = Y v/√2: −i m_ℓ/v (γ-slot P_R)
        m_ell = sp.Symbol("m_ell", positive=True)
        rule = fermion_feynman_rule(coeff_h, diracPR, (h,))
        rule_mass = rule.subs(Y[i, j], sp.sqrt(2) * m_ell / v.s)
        assert sp.simplify(rule_mass + sp.I * m_ell / v.s * diracPR) == 0


class TestGaugeCurrents:
    def test_w_lepton_current(self, sm_leptons):
        """W⁺ ν̄_L γ^μ P_L e_L with coupling g/√2 (from T± = (T1 ± iT2))."""
        SU2L, U1Y, H, Ll, eR, v, gw, g1 = sm_leptons
        g = gw.s
        current = fermion_gauge_current(Ll, i, gauge_groups=[SU2L])

        # rotate W1, W2 → W± ;  W3 stays
        W1, W2, W3 = SU2L.bosons().components
        Wp, Wm = sp.symbols("Wp Wm")
        U = sp.Matrix([[1, -sp.I], [1, sp.I]]) / sp.sqrt(2)
        sub = Rotation([W1, W2], [Wp, Wm], U, kind="unitary").substitution()
        current = sp.expand(current.xreplace(sub))

        table = extract_fermion_vertices(current, [Wp, Wm, W3])
        nuLbar, eLbar = Ll.bar_components
        nuL, eL = Ll.components
        mu = sp.Symbol("mu", integer=True)
        gamma_L = DiracGamma(mu) * diracPL

        # ν̄ γ P_L e with W+: coupling g/√2
        key = (nuLbar[i], gamma_L, eL[i])
        coeff = table[key][1][(Wp,)]
        rule = fermion_feynman_rule(coeff, gamma_L, (Wp,))
        assert sp.simplify(rule - sp.I * g / sp.sqrt(2) * gamma_L) == 0
        # and the conjugate current with W−
        key = (eLbar[i], gamma_L, nuL[i])
        coeff = table[key][1][(Wm,)]
        assert sp.simplify(coeff - g / sp.sqrt(2)) == 0

    def test_neutral_current_charges(self, sm_leptons):
        """Z ℓ̄ℓ ∝ (T³ − Q s²_W); photon couples with Q e."""
        SU2L, U1Y, H, Ll, eR, v, gw, g1 = sm_leptons
        g, gp = gw.s, g1.s
        current = (fermion_gauge_current(Ll, i)
                   + fermion_gauge_current(eR, i))

        W1, W2, W3 = SU2L.bosons().components
        B = U1Y.bosons().components[0]
        Z, A = sp.symbols("Z A", real=True)
        thetaW = sp.atan(gp / g)
        sub = Rotation([W3, B], [Z, A],
                       rotation_2x2(-thetaW)).substitution()
        current = sp.expand(current.xreplace(sub))

        table = extract_fermion_vertices(current, [Z, A, W1, W2])
        mu = sp.Symbol("mu", integer=True)
        gamma_L = DiracGamma(mu) * diracPL
        gamma_R = DiracGamma(mu) * diracPR

        nuLbar, eLbar = Ll.bar_components
        nuL, eL = Ll.components
        eRbar, eRc = eR.bar_components[0], eR.components[0]

        gz = sp.sqrt(g**2 + gp**2)
        sw2 = gp**2 / (g**2 + gp**2)
        e_em = g * gp / gz

        # photon: charged lepton couples with −e (Q = −1), both chiralities
        assert sp.simplify(table[(eLbar[i], gamma_L, eL[i])][1][(A,)]
                           + e_em) == 0
        assert sp.simplify(table[(eRbar[i], gamma_R, eRc[i])][1][(A,)]
                           + e_em) == 0
        # photon–neutrino: absent
        assert (A,) not in table[(nuLbar[i], gamma_L, nuL[i])].get(1, {})

        # Z couplings: gz (T³ − Q s²_W)
        for key, T3, Q, gamma in (
                ((nuLbar[i], gamma_L, nuL[i]), sp.Rational(1, 2), 0, gamma_L),
                ((eLbar[i], gamma_L, eL[i]), -sp.Rational(1, 2), -1, gamma_L),
                ((eRbar[i], gamma_R, eRc[i]), 0, -1, gamma_R)):
            coeff = table[key][1][(Z,)]
            expected = gz * (T3 - Q * sw2)
            assert sp.simplify(coeff - expected) == 0, (key, coeff, expected)


class TestDiagonalization:
    def test_svd_2x2(self):
        M = sp.Matrix([[3, 1], [1, sp.Rational(3, 2)]])
        eL = sp.symbols("e1L e2L")
        eRs = sp.symbols("e1R e2R")
        eLp = sp.symbols("e1Lp e2Lp")
        eRp = sp.symbols("e1Rp e2Rp")
        rotL, rotR = diagonalize_svd(M, eL, eRs, eLp, eRp)
        D = rotL.matrix * M * rotR.matrix.T
        assert sp.simplify(D[0, 1]) == 0
        assert sp.simplify(D[1, 0]) == 0
        assert D[0, 0] >= 0 and D[1, 1] >= 0
        # singular values match M Mᵀ eigenvalues
        eigs = sorted((M * M.T).eigenvals())
        svals = sorted([D[0, 0] ** 2, D[1, 1] ** 2])
        for s2, e in zip(svals, eigs):
            assert sp.simplify(s2 - e) == 0

    def test_svd_2x2_analytic_matches_svd(self):
        """diagonalize_svd_2x2 (analytic tan-2θ route) agrees with
        diagonalize_svd on the pinned numeric case: zero off-diagonals,
        same |singular values|, and each angle satisfies its own
        angle_relation."""
        M = sp.Matrix([[3, 1], [1, sp.Rational(3, 2)]])
        eL = sp.symbols("a1L a2L")
        eRs = sp.symbols("a1R a2R")
        eLp = sp.symbols("a1Lp a2Lp")
        eRp = sp.symbols("a1Rp a2Rp")
        thL, thR = sp.symbols("thL_svd thR_svd", real=True)

        rotL, rotR = diagonalize_svd_2x2(M, eL, eRs, eLp, eRp,
                                         angle_left=thL, angle_right=thR)
        # angles satisfy their defining tan-2θ relations
        for rot, th in ((rotL, thL), (rotR, thR)):
            rel = rot.angle_relation.subs(th, rot.angle_solution)
            # Eq may auto-evaluate to BooleanTrue on substitution
            assert rel is sp.true or sp.simplify(rel.lhs - rel.rhs) == 0

        D = (rotL.matrix * M * rotR.matrix.T).subs(
            {thL: rotL.angle_solution, thR: rotR.angle_solution})
        assert sp.simplify(D[0, 1]) == 0
        assert sp.simplify(D[1, 0]) == 0
        # |singular values| match the general-SVD route
        rotL2, rotR2 = diagonalize_svd(M, eL, eRs, eLp, eRp)
        D2 = rotL2.matrix * M * rotR2.matrix.T
        svals_analytic = sorted([abs(float(D[0, 0])), abs(float(D[1, 1]))])
        svals_general = sorted([abs(float(D2[0, 0])), abs(float(D2[1, 1]))])
        for a, b in zip(svals_analytic, svals_general):
            assert abs(a - b) < 1e-10

    def test_svd_2x2_symbolic_off_diagonal(self):
        """Symbolic triangular case [[a,0],[b,c]] (the vector-like-fermion
        mass-matrix shape): off-diagonals of U_L M U_Rᵀ vanish at random
        numeric points."""
        a, b, c = sp.symbols("svd_a svd_b svd_c", positive=True)
        M = sp.Matrix([[a, 0], [b, c]])
        eL = sp.symbols("b1L b2L")
        eRs = sp.symbols("b1R b2R")
        eLp = sp.symbols("b1Lp b2Lp")
        eRp = sp.symbols("b1Rp b2Rp")

        rotL, rotR = diagonalize_svd_2x2(M, eL, eRs, eLp, eRp)
        D = rotL.matrix * M * rotR.matrix.T
        ok, diff = numeric_equal(D[0, 1], sp.S.Zero, [a, b, c])
        assert ok, diff
        ok, diff = numeric_equal(D[1, 0], sp.S.Zero, [a, b, c])
        assert ok, diff

    def test_takagi_toy_seesaw(self):
        mD, MR = sp.Rational(1, 10), sp.Integer(100)
        M = sp.Matrix([[0, mD], [mD, MR]])
        U, D = diagonalize_takagi(M)
        # M = U D Uᵀ reconstruction
        assert sp.simplify(U * D * U.T - M) == sp.zeros(2, 2)
        # non-negative masses
        assert D[0, 0] >= 0 and D[1, 1] >= 0
        # light eigenvalue ≈ seesaw formula mD²/MR
        light = min(D[0, 0], D[1, 1])
        seesaw = -seesaw_light_mass(sp.Matrix([[mD]]), sp.Matrix([[MR]]))[0, 0]
        assert abs(float(light - seesaw)) < float(seesaw) * (mD / MR) ** 2 * 10

    def test_takagi_requires_symmetric(self):
        with pytest.raises(ValueError):
            diagonalize_takagi(sp.Matrix([[0, 1], [2, 0]]))


class TestRotatedBilinearExtraction:
    """Regression for the bilinear-distribution gap: a fermion mass-basis
    Rotation (Indexed old fields) xreplace'd into a Lagrangian leaves
    Add-valued legs inside Bilinear slots; extract_fermion_vertices and
    fermion_mass_matrix must distribute them (via expand_bilinear, moved
    from invariance.py) instead of silently grouping by composite keys."""

    th = sp.Symbol("th_rot", real=True)

    def _rotated_current(self):
        psiA = WeylFermion("rbA", reps={}, chirality="L", nflavors=1,
                           component_names=["rbA"])
        psiB = WeylFermion("rbB", reps={}, chirality="L", nflavors=1,
                           component_names=["rbB"])
        Zb = sp.Symbol("Zb", real=True)
        mu = sp.Symbol("mu", integer=True)
        gamma_L = DiracGamma(mu) * diracPL

        A, B = psiA.components[0], psiB.components[0]
        Abar, Bbar = psiA.bar_components[0], psiB.bar_components[0]
        n1, n2 = sp.IndexedBase("rb_n1"), sp.IndexedBase("rb_n2")
        n1bar, n2bar = sp.IndexedBase("rb_n1bar"), sp.IndexedBase("rb_n2bar")

        R = rotation_2x2(self.th)
        sub = Rotation([A[i], B[i]], [n1[i], n2[i]], R).substitution()
        sub.update(Rotation([Abar[i], Bbar[i]], [n1bar[i], n2bar[i]],
                            R).substitution())
        return (psiA, psiB, Zb, gamma_L, (n1, n2, n1bar, n2bar), sub)

    def test_extraction_splits_rotated_legs(self):
        psiA, psiB, Zb, gamma_L, (n1, n2, n1bar, n2bar), sub = \
            self._rotated_current()
        A, Abar = psiA.components[0], psiA.bar_components[0]
        gz = sp.Symbol("gz", positive=True)

        L = gz * Zb * Bilinear(Abar[i], gamma_L, A[i])
        L_rot = L.xreplace(sub)
        table = extract_fermion_vertices(L_rot, [Zb])

        c, s = sp.cos(self.th), sp.sin(self.th)
        # old = Rᵀ·new: A → c n1 − s n2, Abar → c n1bar − s n2bar
        expected = {(n1bar[i], n1[i]): gz * c**2,
                    (n1bar[i], n2[i]): -gz * s * c,
                    (n2bar[i], n1[i]): -gz * s * c,
                    (n2bar[i], n2[i]): gz * s**2}
        assert len(table) == 4
        for (bar, gamma, field), coeffs in table.items():
            # every key leg must be a plain Indexed, never an Add
            assert isinstance(bar, sp.Indexed), bar
            assert isinstance(field, sp.Indexed), field
            assert gamma == gamma_L
            got = coeffs[1][(Zb,)]
            assert sp.simplify(got - expected[(bar, field)]) == 0

    def test_mass_matrix_of_rotated_term(self):
        psiA, psiB, Zb, gamma_L, (n1, n2, n1bar, n2bar), sub = \
            self._rotated_current()
        A, Abar = psiA.components[0], psiA.bar_components[0]
        m1 = sp.Symbol("m1_rot", positive=True)

        L = -m1 * Bilinear(Abar[i], diracPR, A[i])
        L_rot = L.xreplace(sub)
        # dummy VEV'd scalar: Vacuum requires one, the term doesn't use it
        S = Scalar("rb_S", real=True)
        S.expand_vev({S.components[0]: sp.Symbol("rb_vS", positive=True)})
        vac = Vacuum([S])

        c, s = sp.cos(self.th), sp.sin(self.th)
        expected = sp.Matrix([[m1 * c**2, -m1 * s * c],
                              [-m1 * s * c, m1 * s**2]])
        bars, fields = (n1bar, n2bar), (n1, n2)
        for a in range(2):
            for b in range(2):
                M = fermion_mass_matrix(L_rot, bars[a], fields[b], vac, 1,
                                        (i, j), gamma=diracPR)
                assert sp.simplify(M[0, 0] - expected[a, b]) == 0, (a, b)


class TestExplicitFlavourIndices:
    """A Yukawa written at explicit generation indices (FEYNLAG_GAPS FG-4).

    ``fermion_mass_matrix`` reads every term at its *own* leg indices, so an
    integer-indexed term feeds only its own entry, a repeated index feeds only
    the diagonal, and symbolic and integer terms mix in one Lagrangian.
    """

    def _pieces(self, sm_leptons):
        SU2L, U1Y, H, Ll, eR, v, gw, g1 = sm_leptons
        return Ll.bar_components[1], eR.components[0], Vacuum([H]), v.s

    def test_diagonal_integer_indices(self, sm_leptons):
        """diag(m_e, m_mu, m_tau) written as three integer-indexed terms."""
        eLbar, eRc, vac, v = self._pieces(sm_leptons)
        SU2L, U1Y, H, Ll, eR, vp, gw, g1 = sm_leptons
        H0 = H.components[1]
        m = sp.symbols("m_e m_mu m_tau", positive=True)
        L = -sum(sp.sqrt(2) * m[a] / v * H0
                 * Bilinear(eLbar[a], diracPR, eRc[a]) for a in range(3))
        M = fermion_mass_matrix(L, eLbar, eRc, vac, 3, (i, j), gamma=diracPR)
        assert sp.simplify(M - sp.diag(*m)) == sp.zeros(3, 3)

    def test_single_off_diagonal_integer_entry(self, sm_leptons):
        """One integer-indexed off-diagonal term populates only that entry."""
        eLbar, eRc, vac, v = self._pieces(sm_leptons)
        SU2L, U1Y, H, Ll, eR, vp, gw, g1 = sm_leptons
        H0 = H.components[1]
        y = sp.Symbol("y13")
        L = -(y + sp.I) * H0 * Bilinear(eLbar[0], diracPR, eRc[2])
        M = fermion_mass_matrix(L, eLbar, eRc, vac, 3, (i, j), gamma=diracPR)
        assert sp.simplify(M[0, 2] - (y + sp.I) * v / sp.sqrt(2)) == 0
        for a in range(3):
            for b in range(3):
                if (a, b) != (0, 2):
                    assert sp.simplify(M[a, b]) == 0

    def test_mixed_symbolic_and_integer_terms(self, sm_leptons):
        """A generic Y[i,j] term plus an integer-indexed correction add up."""
        eLbar, eRc, vac, v = self._pieces(sm_leptons)
        SU2L, U1Y, H, Ll, eR, vp, gw, g1 = sm_leptons
        H0 = H.components[1]
        Y, eps = sp.IndexedBase("Ymix"), sp.Symbol("eps")
        L = -(Y[i, j] * H0 * Bilinear(eLbar[i], diracPR, eRc[j])
              + eps * H0 * Bilinear(eLbar[1], diracPR, eRc[0]))
        M = fermion_mass_matrix(L, eLbar, eRc, vac, 3, (i, j), gamma=diracPR)
        for a in range(3):
            for b in range(3):
                extra = eps if (a, b) == (1, 0) else 0
                assert sp.simplify(M[a, b]
                                   - (Y[a, b] + extra) * v / sp.sqrt(2)) == 0

    def test_repeated_index_is_diagonal(self, sm_leptons):
        """ψ̄_i χ_i (one index on both legs) is a diagonal mass, not a full one."""
        eLbar, eRc, vac, v = self._pieces(sm_leptons)
        k = sp.Symbol("k_diag", positive=True)
        M = fermion_mass_matrix(-k * Bilinear(eLbar[i], diracPR, eRc[i]),
                                eLbar, eRc, vac, 3, (i, j), gamma=diracPR)
        assert sp.simplify(M - k * sp.eye(3)) == sp.zeros(3, 3)


class TestNumericSVD:
    """FG-6: ``diagonalize_svd`` on a complex / >2×2 numeric matrix goes
    through mpmath's complex SVD and returns unitary rotations with
    ``R_L M R_R† = diag(m ≥ 0)``, masses ascending (the symbolic route built
    ``M Mᵀ`` and returned a non-unitary ``U_L`` with complex "masses")."""

    M = sp.Matrix([[3 + sp.I, 1, sp.I / 2], [sp.Rational(1, 2), 2 - sp.I, 1],
                   [0, 3 * sp.I / 10, 5]])

    @staticmethod
    def _syms(tag, n=3):
        return [list(sp.symbols(f"{tag}_{s}0:{n}"))
                for s in ("l", "r", "L", "R")]

    @staticmethod
    def _numpy_svals(M):
        import numpy as np
        A = np.array(sp.N(M).tolist(), dtype=complex)
        return sorted(np.linalg.svd(A, compute_uv=False))

    def _check_biunitary(self, M, rotL, rotR, tol=sp.Float("1e-40")):
        n = M.rows
        for rot in (rotL, rotR):
            assert rot.kind == "unitary"
            dev = rot.matrix * rot.matrix.H - sp.eye(n)
            assert max(abs(sp.N(x)) for x in dev) < tol
        D = rotL.matrix * M * rotR.matrix.H
        for a in range(n):
            for b in range(n):
                if a != b:
                    assert abs(sp.N(D[a, b])) < tol
        masses = [sp.re(D[a, a]) for a in range(n)]
        assert all(abs(sp.im(D[a, a])) < tol for a in range(n))
        assert masses == sorted(masses) and all(m >= 0 for m in masses)
        return masses

    def test_complex_3x3_matches_numpy(self):
        rotL, rotR = diagonalize_svd(self.M, *self._syms("c"))
        masses = self._check_biunitary(self.M, rotL, rotR)
        for m, s in zip(masses, self._numpy_svals(self.M)):
            assert abs(float(m) - s) < 1e-12

    def test_float_complex_input_is_numeric(self):
        """The literal FG-6 reproducer (Python complex floats)."""
        M = sp.Matrix([[3.0 + 1.0j, 1.0, 0.5j], [0.5, 2.0 - 1.0j, 1.0],
                       [0.0, 0.3j, 5.0]])
        rotL, rotR = diagonalize_svd(M, *self._syms("f"))
        # the entries carry double precision only
        self._check_biunitary(M, rotL, rotR, tol=sp.Float("1e-14"))

    def test_exact_gaussian_rational_finishes(self):
        import time
        t0 = time.time()
        diagonalize_svd(self.M, *self._syms("g"))
        assert time.time() - t0 < 10

    def test_real_float_symbolic_route_no_crash(self):
        """The symbolic route used to raise ``TypeError`` on the right-row
        sign fix (immutable matrix) for a float input."""
        M = sp.Matrix([[3.0, -1.0], [1.0, -1.5]])
        rotL, rotR = diagonalize_svd(M, *self._syms("s", 2),
                                     method="symbolic")
        D = rotL.matrix * M * rotR.matrix.T
        assert abs(D[0, 1]) < 1e-12 and abs(D[1, 0]) < 1e-12
        assert D[0, 0] >= 0 and D[1, 1] >= 0

    def test_symbolic_route_rejects_complex(self):
        with pytest.raises(ValueError, match="real matrices"):
            diagonalize_svd(self.M, *self._syms("x"), method="symbolic")

    def test_unknown_method(self):
        with pytest.raises(ValueError, match="unknown SVD method"):
            diagonalize_svd(self.M, *self._syms("u"), method="lapack")

    def test_exact_2x2_stays_symbolic(self):
        M = sp.Matrix([[3, 1], [1, sp.Rational(3, 2)]])
        rotL, _ = diagonalize_svd(M, *self._syms("e", 2))
        assert rotL.kind == "orthogonal" and not rotL.matrix.has(sp.Float)

    def test_zero_singular_value_is_exact(self):
        M = sp.Matrix([[1, 2, sp.I], [2, 4, 2 * sp.I], [0, 1, 3]])  # rank 2
        rotL, rotR = diagonalize_svd(M, *self._syms("z"))
        masses = self._check_biunitary(M, rotL, rotR)
        assert abs(masses[0]) < 1e-40
        from feynlag.vacuum.diagonalize import _numeric_svd
        assert _numeric_svd(M, 50)[2][0] == 0      # an exact zero, not noise

    def test_rotated_mass_term_is_diagonal(self):
        """End to end: rotate a complex 3×3 Dirac mass term with ``rot`` on
        the field legs and ``rot.bar`` on the bar legs; ``fermion_mass_matrix``
        of the result is ``diag(m)`` (and its h.c. half ``diag(m)`` too)."""
        qL = WeylFermion("nsvL", reps={}, chirality="L", nflavors=3,
                         component_names=["nsvL"])
        qR = WeylFermion("nsvR", reps={}, chirality="R", nflavors=3,
                         component_names=["nsvR"])
        L_, R_ = qL.components[0], qR.components[0]
        Lb, Rb = qL.bar_components[0], qR.bar_components[0]
        M = self.M
        lag = -sum(M[a, b] * Bilinear(Lb[a], diracPR, R_[b])
                   + sp.conjugate(M[a, b]) * Bilinear(Rb[b], diracPL, L_[a])
                   for a in range(3) for b in range(3))

        nL, nR = sp.IndexedBase("nsv_chiL"), sp.IndexedBase("nsv_chiR")
        nLb, nRb = sp.IndexedBase("nsv_chiLbar"), sp.IndexedBase("nsv_chiRbar")
        rotL, rotR = diagonalize_svd(M, [L_[k] for k in range(3)],
                                     [R_[k] for k in range(3)],
                                     [nL[k] for k in range(3)],
                                     [nR[k] for k in range(3)])
        sub = {}
        for rot in (rotL, rotR,
                    rotL.bar([Lb[k] for k in range(3)],
                             [nLb[k] for k in range(3)]),
                    rotR.bar([Rb[k] for k in range(3)],
                             [nRb[k] for k in range(3)])):
            sub.update(rot.substitution())
        lag_rot = lag.xreplace(sub)

        masses = self._numpy_svals(M)
        # a spectator VEV: Vacuum needs one, the bare mass term ignores it
        S = Scalar("nsvS", reps={}, component_names=["nsvS"], real=True)
        S.expand_vev({S.components[0]: sp.Symbol("w_nsv", positive=True)})
        vac = Vacuum([S])
        for bar, field, gamma in ((nLb, nR, diracPR), (nRb, nL, diracPL)):
            D = fermion_mass_matrix(lag_rot, bar, field, vac, 3, None,
                                    gamma=gamma)
            for a in range(3):
                for b in range(3):
                    want = masses[a] if a == b else 0
                    assert abs(complex(sp.N(D[a, b])) - want) < 1e-12

    def test_ckm_unitary_and_matches_numpy(self):
        """``V = R_uL · R_dL†`` (the left rotations of ``−Q̄ Y H f_R``) is
        unitary, and ``|V|`` agrees with an independent numpy SVD."""
        import numpy as np
        Yu = sp.Matrix([[sp.Rational(1, 100), sp.I / 50, 0],
                        [sp.Rational(1, 30), sp.Rational(1, 4), sp.I / 10],
                        [0, sp.Rational(1, 20), 1]])
        Yd = sp.Matrix([[sp.Rational(1, 500) + sp.I / 1000, sp.Rational(1, 200), 0],
                        [0, sp.Rational(1, 50), sp.Rational(1, 25)],
                        [sp.I / 100, 0, sp.Rational(1, 40)]])
        rl_u, _ = diagonalize_svd(Yu, *self._syms("cu"))
        rl_d, _ = diagonalize_svd(Yd, *self._syms("cd"))
        V = rl_u.matrix * rl_d.matrix.H
        assert max(abs(sp.N(x)) for x in V * V.H - sp.eye(3)) < 1e-40

        def left(Y):
            U, S, _ = np.linalg.svd(np.array(sp.N(Y).tolist(), dtype=complex))
            return U[:, np.argsort(S)]
        V_np = left(Yu).conj().T @ left(Yd)
        V_abs = np.array([[abs(complex(V[a, b])) for b in range(3)]
                          for a in range(3)])
        assert np.allclose(V_abs, abs(V_np), atol=1e-12)

    def test_bar_rotation_is_conjugate(self):
        U = sp.Matrix([[1, sp.I], [sp.I, 1]]) / sp.sqrt(2)
        a, b, c, d = sp.symbols("bra brb brc brd")
        rot = Rotation([a, b], [c, d], U, kind="unitary")
        rb = rot.bar([a, b], [c, d])
        assert rb.kind == "unitary" and rb.matrix == U.conjugate()
        real = Rotation([a, b], [c, d], rotation_2x2(sp.Symbol("t", real=True)))
        assert real.bar([a, b], [c, d]).matrix == real.matrix
