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

Z0 = 50.0  # Bezugsimpedanz in Ohm
HEIGHTS = range(1, 11)  # Antennenhöhen 1 m bis 10 m

NEC_TEMPLATE = """CM 80 m NVIS dipole {h} m above average ground (Sommerfeld, GN 2)
CE
GW 1 31 -19.6 0 {h} 19.6 0 {h} 0.001026
GE 1
GN 2 0 0 0 13 0.005
EX 0 1 16 0 1 0
FR 0 31 0 0 3.5 0.01
RP 0 46 73 1000 0 0 2 5
EN
"""

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")

def parse_nec_output(out_file: str, z0: float = 50.0):
    freqs, swrs, impedances = [], [], []
    freq_mhz = None
    in_input_section = False

    with open(out_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

    return freqs, swrs, impedances

def create_plot(height: int, freqs, swrs, impedances, output_png: str):
    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} Ω)")

    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")

    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"),
    )

    y_max = min(max(swrs) * 1.15, max(10.0, min_swr * 1.3))
    ax.set_title(f"SWR-Verlauf – 80 m NVIS-Dipol ({height} 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, y_max)
    ax.grid(True, which="both", linestyle="--", alpha=0.4)
    ax.legend(loc="upper right")

    plt.tight_layout()
    plt.savefig(output_png)
    plt.close(fig)
    return min_f, min_swr, min_r, min_x

def main():
    with tempfile.TemporaryDirectory() as tmpdir:
        for h in HEIGHTS:
            nec_path = os.path.join(tmpdir, f"sim_{h}.nec")
            out_path = os.path.join(tmpdir, f"sim_{h}.out")

            with open(nec_path, "w", encoding="utf-8") as f:
                f.write(NEC_TEMPLATE.format(h=h))

            subprocess.run(["nec2c", "-i", nec_path, "-o", out_path], check=True)
            freqs, swrs, impedances = parse_nec_output(out_path, Z0)

            if not freqs:
                raise RuntimeError(f"Keine Frequenzdaten für Höhe {h} m gefunden.")

            output_png = f"swr_nvis80_{h}m.png"
            min_f, min_swr, min_r, min_x = create_plot(h, freqs, swrs, impedances, output_png)
            print(f"{output_png:18s} | Min-SWR: {min_swr:5.2f} @ {min_f:.3f} MHz | Z = {min_r:5.1f} {min_x:+5.1f}j Ω")

if __name__ == "__main__":
    main()
