# /// script
# requires-python = ">=3.10"
# dependencies = ["matplotlib"]
# ///
"""Filtergeschwindigkeit ueber dem eingestellten Volumenstrom (AFM-Poolfilter)."""

import math

import matplotlib.pyplot as plt

DURCHMESSER_MM = [400, 500, 800]
Q_MAX = 30.0
Q_KURVE = [i * 0.1 for i in range(1, int(Q_MAX * 10) + 1)]
V_MIN, V_MAX = 15.0, 30.0
V_RUECK_MIN, V_RUECK_MAX = 40.0, 50.0

fig, ax = plt.subplots(figsize=(10, 6.5))
farben = ["#1f77b4", "#2ca02c", "#d62728"]

BEREICHE = [
    (15, 30, "#1aa39a", 0.20, "AFM  15–30 m/h"),
    (20, 30, "#d9b06a", 0.45, "Filtersand  20–30 m/h"),
    (40, 50, "#7a7368", 0.40, "Rückspülung  40–50 m/h"),
]
for v_lo, v_hi, farbe_b, alpha_b, text_b in BEREICHE:
    ax.axhspan(v_lo, v_hi, color=farbe_b, alpha=alpha_b, zorder=0)
    ax.axhline(v_lo, color=farbe_b, lw=0.8, alpha=0.7, zorder=1)
    ax.axhline(v_hi, color=farbe_b, lw=0.8, alpha=0.7, zorder=1)

print(f"{'Ø [mm]':>7}{'A [m²]':>9}{'Q bei 15 m/h':>15}{'Q bei 30 m/h':>15}")
for i, (d_mm, farbe) in enumerate(zip(DURCHMESSER_MM, farben)):
    flaeche = math.pi * (d_mm / 1000) ** 2 / 4  # m^2
    ax.plot(Q_KURVE, [q / flaeche for q in Q_KURVE], color=farbe, lw=2,
            label=f"Ø {d_mm} mm  (A = {flaeche:.3f} m²)")

    q_lo, q_hi = V_MIN * flaeche, V_MAX * flaeche
    for q, v, off in ((q_lo, V_MIN, (-26, -13)), (q_hi, V_MAX, (6, 8))):
        ax.plot(q, v, "o", color=farbe, ms=6, zorder=3)
        ax.annotate(f"{q:.1f}", (q, v), textcoords="offset points",
                    xytext=off, fontsize=8, color=farbe, zorder=4)
    y_bar = 11.0 - i * 3.0
    ax.hlines(y_bar, q_lo, q_hi, color=farbe, lw=4, alpha=0.85, zorder=2)
    ax.annotate(f"Filterbetrieb: {q_lo:.1f}–{q_hi:.1f} m³/h", (q_hi, y_bar),
                textcoords="offset points", xytext=(8, -3), fontsize=8, color=farbe)

    r_lo, r_hi = V_RUECK_MIN * flaeche, V_RUECK_MAX * flaeche
    for q, v, off in ((r_lo, V_RUECK_MIN, (-26, 6)), (r_hi, V_RUECK_MAX, (6, 6))):
        ax.plot(q, v, "s", color=farbe, ms=6, zorder=3)
        ax.annotate(f"{q:.1f}", (q, v), textcoords="offset points",
                    xytext=off, fontsize=8, color=farbe, zorder=4)
    y_rbar = 37.2 - i * 2.0
    ax.hlines(y_rbar, r_lo, r_hi, color=farbe, lw=4, alpha=0.85, zorder=2,
              linestyle=(0, (4, 2)))
    ax.annotate(f"Rückspülung: {r_lo:.1f}–{r_hi:.1f} m³/h", (r_hi, y_rbar),
                textcoords="offset points", xytext=(8, -3), fontsize=8, color=farbe)
    print(f"{d_mm:>7}{flaeche:9.3f}{q_lo:15.1f}{q_hi:15.1f}")

LABEL_Y = {"AFM  15–30 m/h": 22.5,
           "Filtersand  20–30 m/h": 27.0,
           "Rückspülung  40–50 m/h": 45.0}
for v_lo, v_hi, farbe_b, alpha_b, text_b in BEREICHE:
    ist_afm = text_b.startswith("AFM")
    ax.text(Q_MAX * 0.985, LABEL_Y[text_b], text_b, ha="right", va="center",
            fontsize=10 if ist_afm else 9, fontweight="bold", color="#222222",
            zorder=10 if ist_afm else 6,
            bbox=dict(boxstyle="round,pad=0.35", facecolor="white",
                      alpha=0.65 if ist_afm else 0.45,
                      edgecolor=farbe_b, linewidth=1.2 if ist_afm else 0.8))

ax.set_title("Pool-Filteranlage: Filtergeschwindigkeit bei eingestelltem Volumenstrom\n"
             "AFM vs. Filtersand vs. Rückspülung")
ax.set_xlabel("eingestellter Volumenstrom Q [m³/h]  →  Stellgröße")
ax.set_ylabel("resultierende Filtergeschwindigkeit v [m/h]")
ax.set_xlim(0, Q_MAX)
ax.set_ylim(0, 60)
ax.set_xticks(list(range(0, int(Q_MAX) + 1, 2)))
ax.set_yticks(list(range(0, 61, 5)))
ax.grid(True, ls="--", alpha=0.5)
leg1 = ax.legend(title="Kesseldurchmesser", loc="upper left")
ax.add_artist(leg1)
patches = [plt.Rectangle((0, 0), 1, 1, color=f, alpha=a)
           for _, _, f, a, _ in BEREICHE]
ax.legend(patches, [t for *_, t in BEREICHE], title="Betriebsbereiche",
          loc="lower right", fontsize=8, title_fontsize=9)
fig.tight_layout()
fig.savefig("afm_filter_diagramm_q_auf_x.png", dpi=150)
