"""
FIGURE: scoreboard — DFD win-column sweep final board.

Pure-visual figure (NO compute). Data read directly from
./WIN_COLUMN.md
(the "Honest read — SWEEP COMPLETE" tally: 1 DFD-WIN + 7 honest TIEs).

Rows  = the 8 contested items.
Cols  = [Rival theory, DFD-WIN, TIE]  (a verdict grid / heatmap).
Color = DFD-WIN (teal) vs TIE (amber). Rival column is grey (their claim).

Run:
  cd . && \
  PYTHONPATH=. \
  python3 figures/make_scoreboard.py
Saves -> figures/scoreboard.png  (150 dpi)
"""
import sys
sys.path.insert(0, ".")

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

# -------------------------------------------------------------------------
# Board data (verbatim from WIN_COLUMN.md). Each row = one contested item.
#   item     : short name of the contested capability
#   rival    : the theory that claimed it solely
#   verdict  : "DFD-WIN" or "TIE"
#   note     : the one-line evidence / DFD edge (the load-bearing number)
# -------------------------------------------------------------------------
ROWS = [
    # MOND is the lone outright DFD-WIN
    dict(item="Galaxy rotation / a₀ / BTFR", rival="MOND",
         verdict="DFD-WIN",
         note="a₀ = 2√α·cH₀ = 1.197×10⁻¹⁰  vs SPARC 1.20 (−0.28%), derived not fit"),
    dict(item="Black-hole entropy  S = A/4", rival="String (Strominger–Vafa)",
         verdict="TIE",
         note="T_DFD = ħκ/2πck_B → S = A_bare/4 for ALL non-extremal (S–V: extremal/BPS only)"),
    dict(item="Consistent quantum gravity / UV", rival="String",
         verdict="TIE",
         note="finite-rank spectral action, k_max=60 forced; Λ=α⁵⁷ param-free, single vacuum"),
    dict(item="Background-independent / discrete QG", rival="LQG",
         verdict="TIE",
         note="60 modes on CP²×S³ derived from SM hypercharge; NO Immirzi knob"),
    dict(item="Measurement problem", rival="Pilot-Wave / Bohm",
         verdict="TIE",
         note="real ψ + absolute time + real-det kernel; native foliation (Bohm bolts it on)"),
    dict(item="Classical gravity tests", rival="GR",
         verdict="TIE",
         note="PPN γ=β=1 → Mercury 42.98″/cy, bend 1.7512″, Shapiro 1.0; +6.7% 2PN edge"),
    dict(item="Electron g−2  (12 digits)", rival="QED / QFT",
         verdict="TIE",
         note="inherits QED loop series; edge: derives α⁻¹=137.03599985 (6 ppb) → param-free a_e"),
    dict(item="EW precision phenomenology", rival="SM",
         verdict="TIE",
         note="sin²θ_W = 3/13 = 0.2308 (−0.19%), N_gen=3 exact, PMNS sin²θ₁₂=0.3184"),
]

N = len(ROWS)

# Colors (publication palette; readable on white)
C_WIN   = "#0f9e75"   # teal  — DFD outright win
C_WIN_BG= "#dbf2e9"
C_TIE   = "#ba7517"   # amber — honest TIE
C_TIE_BG= "#fbeed9"
C_RIVAL = "#6f6f6f"   # grey  — rival's former claim
C_RIVAL_BG = "#ececec"
C_INK   = "#222222"
C_MUTE  = "#666666"

# -------------------------------------------------------------------------
# Layout
# -------------------------------------------------------------------------
fig, ax = plt.subplots(figsize=(13.6, 7.6))
ax.set_xlim(0, 100)
ax.set_ylim(0, 100)
ax.axis("off")

# Column x-positions (left edges) for the three verdict cells
col_rival_x, col_rival_w = 33.0, 16.5
col_win_x,   col_win_w   = 50.5, 10.5
col_tie_x,   col_tie_w   = 62.0, 8.5
note_x = 71.5  # evidence text starts here

# Row geometry
top, bot = 80.5, 8.0
row_h = (top - bot) / N
def row_y(i):  # center y of row i (0 = first item at top)
    return top - (i + 0.5) * row_h

# ---- Title block --------------------------------------------------------
ax.text(2.0, 95.5, "Rival win-columns: EMPTY",
        fontsize=23, fontweight="bold", color=C_INK, ha="left", va="center")
ax.text(2.0, 90.6,
        "Every contested item is a DFD-WIN or an honest TIE — no rival theory keeps anything solely its own.",
        fontsize=12.5, color=C_MUTE, ha="left", va="center")

# Score chips (1 WIN + 7 TIE)
chip = FancyBboxPatch((2.0, 84.4), 13.0, 3.6,
                      boxstyle="round,pad=0.15,rounding_size=0.8",
                      linewidth=0, facecolor=C_WIN_BG, zorder=2)
ax.add_patch(chip)
ax.text(8.5, 86.2, "1  DFD-WIN", fontsize=12, fontweight="bold",
        color=C_WIN, ha="center", va="center")
chip2 = FancyBboxPatch((16.0, 84.4), 13.5, 3.6,
                       boxstyle="round,pad=0.15,rounding_size=0.8",
                       linewidth=0, facecolor=C_TIE_BG, zorder=2)
ax.add_patch(chip2)
ax.text(22.75, 86.2, "7  honest TIEs", fontsize=12, fontweight="bold",
        color=C_TIE, ha="center", va="center")

# ---- Column headers -----------------------------------------------------
hy = top + 1.4
ax.text(2.0, hy, "Contested item", fontsize=12.5, fontweight="bold",
        color=C_INK, ha="left", va="center")
ax.text(col_rival_x + col_rival_w/2, hy, "Rival's claim", fontsize=12.5,
        fontweight="bold", color=C_INK, ha="center", va="center")
ax.text(col_win_x + col_win_w/2, hy, "DFD-WIN", fontsize=12.5,
        fontweight="bold", color=C_WIN, ha="center", va="center")
ax.text(col_tie_x + col_tie_w/2, hy, "TIE", fontsize=12.5,
        fontweight="bold", color=C_TIE, ha="center", va="center")
ax.text(note_x, hy, "Evidence  /  DFD edge", fontsize=12.5,
        fontweight="bold", color=C_INK, ha="left", va="center")

# header underline
ax.plot([2.0, 98.0], [top + 0.2, top + 0.2], color="#cccccc", lw=1.0, zorder=1)

# -------------------------------------------------------------------------
# Draw rows
# -------------------------------------------------------------------------
cell_h = row_h * 0.74
def cell(x, w, y, facecolor, edgecolor, text, tcolor, fontsize=12.5,
         fontweight="bold", check=False):
    patch = FancyBboxPatch((x, y - cell_h/2), w, cell_h,
                           boxstyle="round,pad=0.02,rounding_size=0.6",
                           linewidth=1.4, edgecolor=edgecolor,
                           facecolor=facecolor, zorder=3)
    ax.add_patch(patch)
    label = ("✓ " + text) if check else text
    ax.text(x + w/2, y, label, fontsize=fontsize, fontweight=fontweight,
            color=tcolor, ha="center", va="center", zorder=4)

for i, r in enumerate(ROWS):
    y = row_y(i)
    win = r["verdict"] == "DFD-WIN"

    # subtle zebra band across the whole row for readability
    if i % 2 == 1:
        ax.add_patch(plt.Rectangle((1.0, y - row_h/2), 97.0, row_h,
                                    facecolor="#f6f6f4", edgecolor="none",
                                    zorder=0))

    # Item name + rival name (left text block)
    ax.text(2.0, y + row_h*0.07, r["item"], fontsize=12.5, fontweight="bold",
            color=C_INK, ha="left", va="center", zorder=4)

    # Rival's-claim cell (grey — they used to own this)
    cell(col_rival_x, col_rival_w, y, C_RIVAL_BG, "#bdbdbd",
         r["rival"], C_RIVAL, fontsize=11.0, fontweight="normal")

    # DFD-WIN column
    if win:
        cell(col_win_x, col_win_w, y, C_WIN, C_WIN, "WIN", "white",
             fontsize=12.5, check=False)
    else:
        ax.text(col_win_x + col_win_w/2, y, "—", fontsize=14,
                color="#cfcfcf", ha="center", va="center", zorder=4)

    # TIE column
    if not win:
        cell(col_tie_x, col_tie_w, y, C_TIE_BG, C_TIE, "TIE", C_TIE,
             fontsize=12.5, check=True)
    else:
        ax.text(col_tie_x + col_tie_w/2, y, "—", fontsize=14,
                color="#cfcfcf", ha="center", va="center", zorder=4)

    # Evidence / edge note (right, wrapped)
    ax.text(note_x, y, r["note"], fontsize=9.6, color="#3a3a3a",
            ha="left", va="center", zorder=4, wrap=True)

# -------------------------------------------------------------------------
# Footer — the headline tally + honesty-guard statement
# -------------------------------------------------------------------------
ax.plot([1.0, 98.0], [bot - 0.8, bot - 0.8], color="#cccccc", lw=1.0)
ax.text(2.0, bot - 3.4,
        "Rival items still solely-theirs: 0.   Board status: EMPTY — 1 DFD-WIN + 7 honest TIEs.",
        fontsize=12.5, fontweight="bold", color=C_INK, ha="left", va="center")
ax.text(2.0, bot - 6.2,
        "Honesty-guard both ways: every TIE is a real reproduction; every deficit stated. No win or obstruction manufactured.   "
        "Source: WIN_COLUMN.md",
        fontsize=10.0, color=C_MUTE, ha="left", va="center")

plt.subplots_adjust(left=0.005, right=0.995, top=0.99, bottom=0.005)
out = "./figures/scoreboard.png"
plt.savefig(out, dpi=150, bbox_inches="tight", facecolor="white")
print("saved:", out)

# ---- self-check: tally must be 1 WIN + 7 TIE over 8 rows ----------------
n_win = sum(r["verdict"] == "DFD-WIN" for r in ROWS)
n_tie = sum(r["verdict"] == "TIE" for r in ROWS)
print(f"rows={len(ROWS)}  DFD-WIN={n_win}  TIE={n_tie}")
assert len(ROWS) == 8, "expected 8 contested items"
assert n_win == 1 and n_tie == 7, "expected 1 WIN + 7 TIE"
print("tally OK: 1 DFD-WIN + 7 TIE")
