"""SM × U(1)_X with a Z′ boson, end to end with feynlag.

The full Standard Model (Higgs + electroweak + lepton + quark/QCD sectors,
as in examples/sm_scalar_gauge.py) extended by an extra abelian gauge factor
U(1)_X with coupling g_X.  The X-charges are the general family-universal
anomaly-free assignment — a linear combination of the two anomaly-free
abelian charges the SM fermion content admits (once three right-handed
neutrinos are added):

    X = a·Y + b·(B−L)

    q_H = a/2          q_L  = −a/2 − b     q_Q  = a/6 + b/3
    q_S = free          q_eR = −a − b       q_uR = 2a/3 + b/3
                        q_νR = −b           q_dR = −a/3 + b/3

Because the Higgs carries X-charge a/2, the Z and Z′ mix at tree level.
New states and the pinned physics (validated in tests/test_u1x.py):

- an SM-singlet complex scalar S (X-charge q_S, VEV v_X) breaks U(1)_X;
  its CP-odd part is the Goldstone eaten by the Z′ (both pseudoscalars come
  out exactly massless: two Goldstones for two massive neutral bosons);
- Higgs-portal coupling λ_HS|H|²|S|² mixes h and s with
      tan 2θ_s = λ_HS v v_X / (λ v² − λ_S v_X²)   [(h, s) ordering];
- the 3×3 neutral gauge block over (W3, B, X) is found by
  ``model.mass_blocks`` and rotated by ``model.diagonalize``: the photon is
  fixed by the unbroken charge, and the remaining Z–Z′ pair mixes with
      tan 2θ′ = 2a g_Z g_X v² / (a²g_X²v² + 4g_X²q_S²v_X² − g_Z²v²),
  m_Z²·m_Z′² = g_Z²g_X²q_S²v²v_X²/4;  a → 0 is the pure B−L limit (θ′ → 0);
- three right-handed neutrinos (required for the B−L anomaly to cancel)
  with a Dirac Yukawa via H̃, giving M_ν = Y_ν v/√2;
- Z′ff couplings = −sinθ′·g_Z(T³ − Q sin²θ_W) + cosθ′·g_X·q_f; the photon
  couplings are exactly the SM ones (the Z–Z′ mixing never touches A).

The X-charges are kept SYMBOLIC (a, b, q_S) — every pipeline stage handles
that (U(1) generators, invariance checking, gauge currents, extraction);
the one exception in the library is UFO export, whose particle table calls
float() on charges, so no UFO directory is written here.

Run:  python examples/sm_u1x.py
"""

import sympy as sp

from feynlag import (
    FL_I, FL_J, DiracGamma, Lagrangian, Model, ParameterSet, SU3, Scalar,
    U1, WeylFermion, conjugate_pair, diracPL, diracPR, electroweak_gauge,
    extract_fermion_vertices, fermion_feynman_rule, fermion_mass_matrix,
    inner, tilde, yukawa,
)


def main():
    # --- symmetries and parameters -------------------------------------
    # SM electroweak gauge groups from feynlag.models; the U(1)_X extension
    # (and QCD colour) are this example's own additions.
    SU2L, U1Y, gw, g1 = electroweak_gauge()
    P = ParameterSet(gw, g1)            # declare once: create + register
    gX = P.external("gX", 0.5, positive=True)
    gs = P.external("gs", 1.22, positive=True)
    U1X = U1("U1X", coupling=gX)
    SU3c = SU3("SU3c", coupling=gs)

    # the two X-charge parameters (symbolic everywhere) and the singlet charge
    aX = P.external("aX", 0.4)
    bX = P.external("bX", -0.7)
    qS = P.external("qS", 1.0)

    v = P.external("v", 246.0, positive=True, unit_dim=1)
    vX = P.external("vX", 2000.0, positive=True, unit_dim=1)
    lam = P.external("lam", 0.129)
    lamS = P.external("lamS", 0.2)
    lamHS = P.external("lamHS", 0.05)
    mu2 = P.internal("mu2", unit_dim=2)
    muS2 = P.internal("muS2", unit_dim=2)

    def qcharge(Y, BmL):
        """The anomaly-free charge map X = a·Y + b·(B−L)."""
        return aX.s * Y + bX.s * BmL

    # --- fields -----------------------------------------------------------
    H = Scalar("H", reps={SU2L: 2, U1Y: sp.Rational(1, 2),
                          U1X: qcharge(sp.Rational(1, 2), 0)},
               component_names=["Gp", "H0"])
    H.expand_vev({H.H0: v})

    # SM-singlet complex scalar: breaks U(1)_X at v_X, gives the Z′ its mass
    S = Scalar("S", reps={U1X: qS.s}, component_names=["S0"])
    S.expand_vev({S.S0: vX})

    Ll = WeylFermion("Ll", reps={SU2L: 2, U1Y: -sp.Rational(1, 2),
                                 U1X: qcharge(-sp.Rational(1, 2), -1)},
                     chirality="L", nflavors=3, component_names=["nuL", "eL"])
    eR = WeylFermion("eR", reps={U1Y: -1, U1X: qcharge(-1, -1)},
                     chirality="R", nflavors=3, component_names=["eR"])
    # right-handed neutrinos: Y = 0, B−L = −1 — they carry ONLY the X charge
    # (needed for the B−L gauge anomaly of the SM fermion content to cancel)
    nuR = WeylFermion("nuR", reps={U1X: qcharge(0, -1)},
                      chirality="R", nflavors=3, component_names=["nuR"])

    QL = WeylFermion("QL", reps={SU2L: 2, U1Y: sp.Rational(1, 6), SU3c: 3,
                                 U1X: qcharge(sp.Rational(1, 6),
                                              sp.Rational(1, 3))},
                     chirality="L", nflavors=3,
                     component_names=["uL_1", "uL_2", "uL_3",
                                      "dL_1", "dL_2", "dL_3"])
    uR = WeylFermion("uR", reps={U1Y: sp.Rational(2, 3), SU3c: 3,
                                 U1X: qcharge(sp.Rational(2, 3),
                                              sp.Rational(1, 3))},
                     chirality="R", nflavors=3,
                     component_names=["uR_1", "uR_2", "uR_3"])
    dR = WeylFermion("dR", reps={U1Y: -sp.Rational(1, 3), SU3c: 3,
                                 U1X: qcharge(-sp.Rational(1, 3),
                                              sp.Rational(1, 3))},
                     chirality="R", nflavors=3,
                     component_names=["dR_1", "dR_2", "dR_3"])

    W, B = SU2L.bosons("W"), U1Y.bosons("B")
    X = U1X.bosons("X")
    G = SU3c.bosons("G")

    # --- Lagrangian (field level) -------------------------------------------
    HdH, SdS = inner(H, H), inner(S, S)
    V = (-mu2 * HdH + lam * HdH**2
         - muS2 * SdS + lamS * SdS**2
         + lamHS * HdH * SdS)

    # Yukawas: each constructor does the gauge contraction, the flavour
    # indices (Y[fl_i, fl_j]) and the + h.c.; colour is a spectator index,
    # and the U(1)_X charges are checked to balance (symbolically) as well
    Ye, Yv, Yu, Yd = (sp.IndexedBase(n) for n in ("Ye", "Yv", "Yu", "Yd"))
    LYuk = yukawa(Ye, Ll, H, eR)                 # −Ye L̄ H e_R + h.c.
    LYukN = yukawa(Yv, Ll, tilde(H), nuR)        # −Yv L̄ H̃ ν_R + h.c.
    LYuk_d = yukawa(Yd, QL, H, dR)               # −Yd Q̄ H d_R + h.c.
    LYuk_u = yukawa(Yu, QL, tilde(H), uR)        # −Yu Q̄ H̃ u_R + h.c.

    L = Lagrangian()
    # (D_μφ)†(D^μφ) for H (W, B and X: it carries all three) and S (X only),
    # and the gauge currents, which pick up X for every field with U1X
    L.add_kinetic(H, S, Ll, eR, nuR, QL, uR, dR)
    L.add(-V, sector="potential")
    L.add(LYuk + LYukN + LYuk_d + LYuk_u, sector="yukawa")

    model = Model("SM-U1X", gauge_groups=[SU2L, U1Y, U1X, SU3c],
                  fields=[H, S, Ll, eR, nuR, QL, uR, dR, W, B, X, G],
                  parameters=P, lagrangian=L)
    print(model.summary())
    print()

    i, j = FL_I, FL_J
    Gp = H.Gp
    nuL, eL, nuLbar, eLbar = Ll.nuL, Ll.eL, Ll.nuLbar, Ll.eLbar
    eRc, eRbar = eR.eR, eR.eRbar
    nuRc, nuRbar = nuR.nuR, nuR.nuRbar
    uL1, uL1bar = QL.uL_1, QL.uL_1bar

    # --- pipeline -----------------------------------------------------------
    report = model.check_invariance()
    print("invariance:", report)
    report.raise_on_failure()
    print("tadpoles:  ", model.solve_tadpoles([mu2, muS2]))

    # --- scalar sector: portal h–s mixing, Goldstone pseudoscalars ----------
    print("\nscalar mass blocks:")
    for block in model.mass_blocks(kind="scalar"):
        print("  ", block)
    scalar_blocks = model.mass_blocks(kind="scalar")
    even = scalar_blocks[0]
    print("\nCP-even scalar M² (h0, s0):")
    sp.pprint(even.matrix)
    # the CP-odd directions H0_i and S0_i have no mass term at all: each is a
    # Goldstone (two of them, eaten by Z and Z′), so they form two 1×1 blocks
    odd = [b for b in scalar_blocks if b.cp == "odd"]
    assert all(b.matrix == sp.zeros(1, 1) and b.goldstones for b in odd)
    print("CP-odd (G0, S0_i) block ≡ 0 — two Goldstones, eaten by Z and Z′")
    G0, aX0 = (b.fields[0] for b in odd)

    # h–s portal mixing through the tan 2θ route; names light first, so h1
    # is the SM-like state at this benchmark (v_X ≫ v)
    thetas = sp.Symbol("thetas", real=True)
    d_s = model.diagonalize(even, names=["h1", "h2"], angle=thetas,
                            order="light_first")
    h1, h2 = d_s.new_fields
    print("scalar mixing:", d_s.angle_relation)

    # --- gauge sector: the model finds the blocks and their rotations ------
    # (charged: W¹,W² → W±; neutral: the 3×3 (W3, B, X) block, whose
    # massless vector — the photon — is fixed by the unbroken charge
    # Q = T3 + Y, leaving the Z–Z′ pair to mix through one tan 2θ′ angle)
    charged_block, neutral_block = model.mass_blocks(kind="gauge")
    print("\ngauge blocks:")
    print("  ", charged_block)
    print("  ", neutral_block)
    M3 = neutral_block.matrix
    print("\nneutral gauge M² (W3, B, X):")
    sp.pprint(M3)
    assert sp.simplify(M3.det()) == 0     # exactly one massless state

    Wp, Wm = model.diagonalize(charged_block, names=["Wp"],
                               conjugate_names=["Wm"]).rotation.new_fields
    # names: massive states first, the photon last.  The result is ONE
    # composed rotation (Z–Z′ mixing on top of the Weinberg rotation); it
    # is verified against the mass matrix before being registered.
    thetap = sp.Symbol("thetap", real=True)
    d_neutral = model.diagonalize(neutral_block, names=["Z", "Zp", "A"],
                                  angle=thetap)
    Z, Zp, A = d_neutral.new_fields
    print("Z–Z′ mixing:", d_neutral.angle_relation)

    # physical masses at the benchmark point
    bench = {gw.s: 0.6535, g1.s: 0.3580, gX.s: 0.5, aX.s: 0.4,
             qS.s: 1.0, v.s: 246.0, vX.s: 2000.0}
    th_num = d_neutral.angle_solution.subs(bench)
    mZ2, mZp2, mA2 = [float(m.subs(thetap, th_num).subs(bench))
                      for m in d_neutral.masses_squared]
    assert mA2 == 0                       # the photon, exactly
    print(f"benchmark: m_Z = {mZ2**0.5:.2f} GeV, m_Z' = {mZp2**0.5:.2f} GeV")

    # --- bosonic Feynman rules -----------------------------------------------
    Gm, cmap = conjugate_pair(Gp, "Gm")
    boson_fields = [h1, h2, G0, aX0, Gp, Gm, Z, A, Zp, Wp, Wm]

    rules = model.feynman_rules(boson_fields, sector="kinetic",
                                conjugate_map=cmap, simplifier=sp.simplify)
    print(f"\n{len(rules)} kinetic-sector vertices; Z′ highlights:")
    for key in [(h1, Zp, Zp), (h1, Z, Zp), (h1, Z, Z)]:
        skey = tuple(sorted(key, key=lambda f: f.sort_key()))
        if skey in rules:
            print(" ", skey, "->", rules[skey])

    # --- neutrino Dirac mass ---------------------------------------------------
    M_nu = fermion_mass_matrix(LYukN, nuLbar, nuRc, model.vacuum, 3, (i, j),
                               gamma=diracPR)
    print("\nDirac neutrino mass matrix M_ν =")
    sp.pprint(M_nu)

    # --- fermion Feynman rules (Z′, shifted Z, unchanged photon, portal h) --
    LYuk_phys = model.physical_lagrangian(sector="yukawa").xreplace(cmap)
    table = extract_fermion_vertices(LYuk_phys, boson_fields)

    mu = sp.Symbol("mu", integer=True)
    gammaL = DiracGamma(mu) * diracPL
    gammaR = DiracGamma(mu) * diracPR

    def show(name, bar, gamma, field, boson):
        entry = table.get((bar, gamma, field), {})
        coeff = entry.get(1, {}).get((boson,), sp.S.Zero)
        rule = sp.simplify(fermion_feynman_rule(coeff, gamma, (boson,)))
        print(f"  {name:12s} ->", rule)

    print("\nZ′ couplings (−sinθ′·g_Z(T³−Q s_w²) + cosθ′·g_X·q_f):")
    show("Z' eL eL", eLbar[i], gammaL, eL[i], Zp)
    show("Z' eR eR", eRbar[i], gammaR, eRc[i], Zp)
    show("Z' nuL nuL", nuLbar[i], gammaL, nuL[i], Zp)
    show("Z' nuR nuR", nuRbar[i], gammaR, nuRc[i], Zp)
    show("Z' uL uL", uL1bar[i], gammaL, uL1[i], Zp)

    print("\nmodified Z couplings (SM recovered at θ′ → 0):")
    show("Z eR eR", eRbar[i], gammaR, eRc[i], Z)
    show("Z nuR nuR", nuRbar[i], gammaR, nuRc[i], Z)

    print("\nphoton couplings (exactly SM — A never mixes with X):")
    show("A eL eL", eLbar[i], gammaL, eL[i], A)
    show("A nuR nuR", nuRbar[i], gammaR, nuRc[i], A)

    print("\nportal-mixed Higgs couplings (cosθ_s/sinθ_s split):")
    show("h1 eL eR", eLbar[i], diracPR, eRc[j], h1)
    show("h2 eL eR", eLbar[i], diracPR, eRc[j], h2)
    show("h1 nuL nuR", nuLbar[i], diracPR, nuRc[j], h1)


if __name__ == "__main__":
    main()
