"""
Figure ew_sin2w — reproduces win_ew_precision.py.

Panel (a): DFD's parameter-free prediction sin^2 theta_W = 3/13 = 0.23077
  (horizontal line) vs the three measured weak-mixing-angle schemes with error
  bars:  MS-bar(M_Z) 0.23121, effective-leptonic 0.23155, on-shell 0.22290.
  Annotates the -0.19% MS-bar agreement and that the rational origin is
  parameter-free but NOT precision-grade (it sits ~11 sigma from MS-bar).

Panel (b): a small table of other DFD-DERIVED Standard-Model inputs vs measured
  (N_gen=3, alpha^-1 to 6 ppb, PMNS sin^2 theta_12 = 0.3184, cos^2 12 cos^2 13 = 2/3).

All numbers are taken verbatim from win_ew_precision.py so the figure is a faithful
reproduction of that script.
"""
import sys
sys.path.insert(0, ".")

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np

# ----------------------------------------------------------------------------
# Numbers verbatim from win_ew_precision.py
# ----------------------------------------------------------------------------
s2w_dfd = 3.0 / 13.0                       # = 0.230769...  parameter-free rational

# (value, 1-sigma error) for each measured scheme  [PDG]
schemes = [
    ("MS-bar ($M_Z$)",       0.23121, 0.00004),
    ("effective-leptonic",   0.23155, 0.00004),
    ("on-shell\n$1-M_W^2/M_Z^2$", 0.22290, 0.00030),
]

# Other DFD-derived SM inputs vs measured (name, DFD, measured, err, note)
rows = [
    ("$N_{\\rm gen}$",                 3.0,           2.984,         0.008,  "Spin$^c$ index (exact)"),
    ("$\\alpha^{-1}$",                 137.03599985,  137.035999084, 1.4e-7, "real-bimodule thm (6 ppb)"),
    ("PMNS $\\sin^2\\theta_{12}$",     0.3184,        0.307,         0.013,  "trimaximal TM1"),
    ("$\\cos^2\\theta_{12}\\cos^2\\theta_{13}$", 2.0/3.0, 0.6610,    0.010,  "$=2/3$ forced"),
]

# ----------------------------------------------------------------------------
# Figure
# ----------------------------------------------------------------------------
plt.rcParams.update({
    "font.size": 11,
    "axes.titlesize": 12,
    "axes.labelsize": 11,
    "figure.dpi": 150,
})

fig = plt.figure(figsize=(12.5, 5.4))
gs = fig.add_gridspec(1, 2, width_ratios=[1.05, 1.0], wspace=0.22)

DFD_COLOR = "#185FA5"   # blue
MEAS_COLOR = "#D85A30"  # coral

# ---------------- Panel (a): weak mixing angle -------------------------------
axa = fig.add_subplot(gs[0, 0])

x = np.arange(len(schemes))
vals = np.array([v for _, v, _ in schemes])
errs = np.array([e for _, _, e in schemes])
labels = [n for n, _, _ in schemes]

# DFD prediction as horizontal line + band (the line itself is exact; no error)
axa.axhline(s2w_dfd, color=DFD_COLOR, lw=2.2, zorder=2,
            label=f"DFD  $3/13 = {s2w_dfd:.5f}$\n(parameter-free rational)")

# measured schemes with error bars
axa.errorbar(x, vals, yerr=errs, fmt="o", ms=9, color=MEAS_COLOR,
             ecolor=MEAS_COLOR, elinewidth=2.0, capsize=6, capthick=2.0,
             zorder=3, label="measured (PDG)")

# annotate each measured point with value and DFD deviation
for xi, (name, v, e) in zip(x, schemes):
    dev_pct = 100.0 * (s2w_dfd - v) / v
    dev_sig = (s2w_dfd - v) / e
    axa.annotate(f"{v:.5f}\n({dev_pct:+.2f}%, {dev_sig:+.0f}$\\sigma$)",
                 (xi, v), textcoords="offset points", xytext=(12, 0),
                 va="center", ha="left", fontsize=9.5, color=MEAS_COLOR)

axa.set_xticks(x)
axa.set_xticklabels(labels, fontsize=10)
axa.set_xlim(-0.6, len(schemes) - 0.05)
axa.set_ylabel(r"$\sin^2\theta_W$")
axa.set_title("(a)  Weak mixing angle: DFD $3/13$ vs measured schemes", loc="left")
axa.grid(axis="y", ls=":", alpha=0.5)

# headline annotation: the -0.19% MS-bar agreement, honest caveat
axa.text(0.5, 0.30,
         r"$\bf{-0.19\%}$ vs MS-bar($M_Z$)" + "\n"
         "parameter-free rational origin\n"
         r"(notable, $\it{not}$ precision-grade:" + "\n"
         r"$\sim 11\sigma$ from the EW fit)",
         transform=axa.transAxes, fontsize=10.5, ha="center", va="center",
         bbox=dict(boxstyle="round,pad=0.5", fc="#E6F1FB", ec=DFD_COLOR, lw=1.2))

axa.legend(loc="upper left", fontsize=9.5, framealpha=0.95)

# ---------------- Panel (b): table of derived SM inputs ----------------------
axb = fig.add_subplot(gs[0, 1])
axb.axis("off")
axb.set_title("(b)  Other DFD-derived SM inputs vs measured", loc="left")

col_labels = ["quantity", "DFD", "measured", "$\\pm$", "dev"]
table_rows = []
cell_colors = []
for name, dfd, meas, err, note in rows:
    dev_pct = 100.0 * (dfd - meas) / meas
    dev_sig = (dfd - meas) / err
    # format DFD and measured to sensible precision per row
    if abs(dfd) > 100:    # alpha^-1
        dfd_s = f"{dfd:.6f}"
        meas_s = f"{meas:.6f}"
        err_s = f"{err:.1e}"
    else:
        dfd_s = f"{dfd:.4f}"
        meas_s = f"{meas:.4f}"
        err_s = f"{err:.3f}"
    dev_s = f"{dev_pct:+.2f}%\n({dev_sig:+.1f}$\\sigma$)"
    table_rows.append([name, dfd_s, meas_s, err_s, dev_s])
    cell_colors.append(["#F4F4F0"] * 5)

tab = axb.table(cellText=table_rows, colLabels=col_labels,
                cellColours=cell_colors,
                colColours=["#CECBF6"] * 5,
                cellLoc="center", loc="center",
                bbox=[0.0, 0.30, 1.0, 0.62])
tab.auto_set_font_size(False)
tab.set_fontsize(10)
tab.scale(1, 2.0)
# widen the quantity column a touch
for (r, c), cell in tab.get_celld().items():
    cell.set_edgecolor("#B4B2A9")
    if c == 0:
        cell.set_width(0.30)
    if r == 0:
        cell.set_text_props(weight="bold", color="#26215C")

# notes under the table
note_lines = [f"$\\bullet$  {name.replace(chr(36),'')[:0]}{note}" for (name, *_ , note) in
              [(n, d, m, e, nt) for (n, d, m, e, nt) in rows]]
notes_txt = "\n".join([
    r"$\bullet$  $N_{\rm gen}=3$ exact (Spin$^c$ index) vs $Z$-width $N_\nu$",
    r"$\bullet$  $\alpha^{-1}=137.03599985$ from minimal real bimodule (6 ppb)",
    r"$\bullet$  PMNS $\sin^2\theta_{12}=0.3184$ trimaximal TM1, parameter-free",
    r"$\bullet$  $\cos^2\theta_{12}\cos^2\theta_{13}=2/3$ forced",
])
axb.text(0.0, 0.245, notes_txt, transform=axb.transAxes, fontsize=9.0,
         va="top", ha="left")

axb.text(0.0, 0.02,
         "DFD derives these SM inputs (the SM fits them) at ~0.1-1%.\n"
         "Verdict: TIE-by-inheritance + derives-the-inputs edge; fewer free parameters.",
         transform=axb.transAxes, fontsize=8.8, va="bottom", ha="left",
         style="italic", color="#5F5E5A")

fig.suptitle("DFD electroweak: $\\sin^2\\theta_W = 3/13 = 0.23077$  (parameter-free, $-0.19\\%$ vs MS-bar)",
             fontsize=13, y=0.99)

fig.subplots_adjust(left=0.07, right=0.985, top=0.90, bottom=0.10, wspace=0.22)
out = "./figures/ew_sin2w.png"
fig.savefig(out, dpi=150, bbox_inches="tight")
print("saved", out)

# ----------------------------------------------------------------------------
# Console confirmation of the headline numbers
# ----------------------------------------------------------------------------
print(f"3/13 = {s2w_dfd:.5f}  (target 0.23077)")
print(f"MS-bar dev = {100*(s2w_dfd-0.23121)/0.23121:+.2f}%  (target -0.19%)")
print(f"2/3 = {2.0/3.0:.5f}  (target 0.66667)")
