import subprocess
import numpy as np
import matplotlib.pyplot as plt

# 1. NEC-Datei für Azimut-Schnitt (Theta = 68° entspricht 22° Elevation)
nec_content = """CM 10m Delta Loop Azimuth 2m Setup
CE
GW 1 11 0 0 2 -1.34 0 6.5 0.0007
GW 2 9 -1.34 0 6.5 1.34 0 6.5 0.0007
GW 3 11 1.34 0 6.5 0 0 2 0.0007
GE 1
GN 2 0 0 0 13 0.005
EK
EX 0 1 1 0 1 0
FR 0 1 0 0 28.5 0
RP 0 1 361 1000 68 0 0 1
EN
"""

with open("pattern_az_2m.nec", "w") as f:
    f.write(nec_content)

# 2. Simulation ausführen
subprocess.run(["nec2c", "-i", "pattern_az_2m.nec", "-o", "pattern_az_2m.out"], stdout=subprocess.DEVNULL)

# 3. Daten für Azimut parsen
angles_rad = []
gains_dbi = []

with open("pattern_az_2m.out", "r") as f:
    lines = f.readlines()
    in_pattern = False
    for line in lines:
        if "RADIATION PATTERNS" in line:
            in_pattern = True
            continue
        
        if in_pattern:
            parts = line.strip().split()
            if len(parts) >= 8:
                try:
                    phi = float(parts[1])
                    total_gain = float(parts[4])
                    
                    angles_rad.append(np.radians(phi))
                    gains_dbi.append(total_gain)
                except ValueError:
                    continue

# 4. Vollständiges 360°-Polardiagramm zeichnen
fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}, figsize=(7, 7))

ax.plot(angles_rad, gains_dbi, color='navy', linewidth=2.5, label='Gain (dBi)')

# Kompass-Konfiguration (0° = Nord/Oben)
ax.set_theta_zero_location("N")
ax.set_theta_direction(-1)

# Dynamikbereich beschränken
ax.set_rlim(-30, 10)
ax.set_rticks([-30, -20, -10, 0, 10])
ax.set_rlabel_position(135)

ax.set_title("10m Delta-Loop (Speisung: 2m) – Horizontales Diagramm (22° Elev.)", pad=20, fontsize=12, fontweight='bold')
ax.grid(True, linestyle='--', alpha=0.6)

plt.savefig("delta_loop_azimuth_2m.png", dpi=300, bbox_inches='tight')
print("Horizontaldiagramm gespeichert als 'delta_loop_azimuth_2m.png'!")
