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

# 1. NEC-Datei schreiben (RP-Karte rechnet nun Theta von 0 bis 90 für Phi=0° und Phi=180°)
nec_content = """CM 10m Delta Loop Symmetrisches Pattern
CE
GW 1 11 0 0 5 -1.34 0 9 0.0007
GW 2 9 -1.34 0 9 1.34 0 9 0.0007
GW 3 11 1.34 0 9 0 0 5 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 91 2 1000 0 0 1 180
EN
"""

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

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

# 3. Daten für Phi = 0° (rechts) und Phi = 180° (links) parsen
data_phi0 = {}
data_phi180 = {}

with open("pattern.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:
                    theta = float(parts[0])
                    phi = float(parts[1])
                    total_gain = float(parts[4])
                    
                    if abs(phi - 0.0) < 0.1:
                        data_phi0[theta] = total_gain
                    elif abs(phi - 180.0) < 0.1:
                        data_phi180[theta] = total_gain
                except ValueError:
                    continue

# 4. Zusammenfügen zu einem 0°-180° Array (von rechts 0° nach links 180°)
angles_deg = []
gains_dbi = []

# Rechts nach Oben: Phi=0°, Theta von 90° runter auf 0° (Elevation 0° bis 90°)
for theta in sorted(data_phi0.keys(), reverse=True):
    elevation = 90.0 - theta
    angles_deg.append(elevation)
    gains_dbi.append(data_phi0[theta])

# Oben nach Links: Phi=180°, Theta von 0° hoch auf 90° (Elevation 90° bis 180°)
for theta in sorted(data_phi180.keys()):
    if theta == 0: continue  # 90° Zenit nicht doppelt hinzufügen
    elevation = 90.0 + theta
    angles_deg.append(elevation)
    gains_dbi.append(data_phi180[theta])

angles_rad = np.radians(angles_deg)

# 5. Polardiagramm zeichnen
fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}, figsize=(8, 5))

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

# Achsen-Konfiguration
ax.set_theta_zero_location("E")  # 0° Horizont rechts
ax.set_theta_direction(1)        # Nach oben bis 180° links
ax.set_thetamin(0)
ax.set_thetamax(180)

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

ax.set_title("10m Delta-Loop – Vollständiges 180° Vertikaldiagramm", pad=20, fontsize=12, fontweight='bold')
ax.grid(True, linestyle='--', alpha=0.6)

plt.savefig("delta_loop_pattern.png", dpi=300, bbox_inches='tight')
print("Vollständiges 180°-Diagramm neu gespeichert!")
