#!/usr/bin/env python3
import math
import re
import matplotlib
matplotlib.use("Agg")  # Headless-Backend für Server ohne X11/GUI
import matplotlib.pyplot as plt

INPUT_FILE = "som_nvis80.out"
OUTPUT_PNG = "swr_nvis80.png"
Z0 = 50.0  # Bezugsimpedanz in Ohm

def calc_swr(r: float, x: float, z0: float = 50.0) -> float:
    num = (r - z0) ** 2 + x ** 2
    den = (r + z0) ** 2 + x ** 2
    gamma = math.sqrt(num / den)
    return (1.0 + gamma) / (1.0 - gamma) if gamma < 1.0 else float("inf")

freqs, swrs, impedances = [], [], []
freq_mhz = None
in_input_section = False

with open(INPUT_FILE, "r", encoding="utf-8", errors="replace") as f:
    for line in f:
        freq_match = re.search(r"FREQUENCY\s*[=:]\s*([0-9.eE+-]+)", line)
        if freq_match:
            freq_mhz = float(freq_match.group(1))

        if "ANTENNA INPUT PARAMETERS" in line:
            in_input_section = True
            continue

        if in_input_section:
            floats = re.findall(r"[+-]?\d+\.\d+[eE][+-]\d+", line)
            if len(floats) >= 6 and freq_mhz is not None:
                r = float(floats[4])
                x = float(floats[5])
                freqs.append(freq_mhz)
                swrs.append(calc_swr(r, x, Z0))
                impedances.append((r, x))
                in_input_section = False

if not freqs:
    raise RuntimeError(f"Keine Frequenzdaten in {INPUT_FILE} gefunden.")

min_idx = min(range(len(swrs)), key=lambda i: swrs[i])
min_f, min_swr = freqs[min_idx], swrs[min_idx]
min_r, min_x = impedances[min_idx]

if min_idx < len(freqs) * 0.2:
    ha, dx = "left", 5
elif min_idx > len(freqs) * 0.8:
    ha, dx = "right", -5
else:
    ha, dx = "center", 0

fig, ax = plt.subplots(figsize=(8, 4.8), dpi=150)
ax.plot(freqs, swrs, color="#1f77b4", linewidth=2, marker="o", markersize=4, label=f"SWR ({Z0:.0f} Ω)")

# Referenzlinien für SWR 1.5 und 2.0
ax.axhline(1.5, color="#2ca02c", linestyle="--", linewidth=1, label="SWR 1.5")
ax.axhline(2.0, color="#d62728", linestyle=":", linewidth=1.2, label="SWR 2.0")

# Minimum mit Fußpunktimpedanz hervorheben
ax.scatter([min_f], [min_swr], color="#ff7f0e", zorder=5, s=50)
ax.annotate(
    f"Min: SWR {min_swr:.2f} @ {min_f:.3f} MHz\n(Z = {min_r:.1f} {min_x:+.1f}j Ω)",
    xy=(min_f, min_swr),
    xytext=(dx, 18),
    textcoords="offset points",
    ha=ha,
    fontsize=8.5,
    bbox=dict(boxstyle="round,pad=0.3", fc="white", ec="#ff7f0e", alpha=0.9),
    arrowprops=dict(arrowstyle="->", color="#ff7f0e"),
)

ax.set_title("SWR-Verlauf – 80 m NVIS-Dipol (3 m Höhe)")
ax.set_xlabel("Frequenz (MHz)")
ax.set_ylabel(f"SWR (Z₀ = {Z0:.0f} Ω)")
ax.set_xlim(min(freqs), max(freqs))
ax.set_ylim(1.0, min(max(swrs) * 1.15, 10.0))
ax.grid(True, which="both", linestyle="--", alpha=0.4)
ax.legend(loc="upper right")

plt.tight_layout()
plt.savefig(OUTPUT_PNG)
print(f"Gespeichert: {OUTPUT_PNG} (Min-SWR {min_swr:.2f} bei {min_f:.3f} MHz)")
