#! /usr/bin/python3
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
from skyfield.api import load, wgs84
from skyfield import almanac

# 1. Ephemeriden und Zeitskala laden
planets = load('de421.bsp')
ts = load.timescale()

# Ortszeit für Muenchen / Deutschland festlegen
local_tz = ZoneInfo("Europe/Berlin")
now_local = datetime.now(local_tz)

# Start und Ende des heutigen Tages (00:00 bis 24:00 Uhr Lokalzeit)
start_of_day = datetime(now_local.year, now_local.month, now_local.day, 0, 0, tzinfo=local_tz)
end_of_day = start_of_day + timedelta(days=1)

# Zeitreihe für das Diagramm (alle 10 Minuten)
minutes = np.arange(0, 24 * 60, 10)
local_datetimes = [start_of_day + timedelta(minutes=int(m)) for m in minutes]
t_plot = ts.from_datetimes(local_datetimes)

# 2. Beobachterort: Minga
earth = planets['earth']
location = wgs84.latlon(+48.173333, +11.635000, elevation_m=520)
minga = earth + location
sun = planets['sun']

# 3. Exakte Auf-/Untergangs- und Daemmerungszeiten berechnen
t0 = ts.from_datetime(start_of_day)
t1 = ts.from_datetime(end_of_day)

# location an die Almanach-Funktion uebergeben
twilight_func = almanac.dark_twilight_day(planets, location)
t_events, y_events = almanac.find_discrete(t0, t1, twilight_func)

# Zuordnung der Zustandsuebergaenge
event_names = {
    (0, 1): "Beginn astron. Daemmerung (-18 Grad)",
    (1, 2): "Beginn naut.   Daemmerung (-12 Grad)",
    (2, 3): "Beginn buerg.  Daemmerung (- 6 Grad)",
    (3, 4): "Sonnenaufgang   (0 Grad)",
    (4, 3): "Sonnenuntergang (0 Grad)",
    (3, 2): "Ende buerg.  Daemmerung (- 6 Grad)",
    (2, 1): "Ende naut.   Daemmerung (-12 Grad)",
    (1, 0): "Ende astron. Daemmerung (-18 Grad)",
}

print(f"=== Zeiten fuer Minga am {now_local.strftime('%d.%m.%Y')} ===")
previous_state = twilight_func(t0).item()

for time_evt, new_state in zip(t_events, y_events):
    transition = (previous_state, new_state)
    name = event_names.get(transition, f"Uebergang {previous_state} -> {new_state}")
    dt_local = time_evt.astimezone(local_tz)
    print(f"{dt_local.strftime('%H:%M:%S')} Uhr | {name}")
    previous_state = new_state

# 4. Positionen für die Kurve berechnen
apparent = minga.at(t_plot).observe(sun).apparent()
alt, az, _ = apparent.altaz()

# 5. Diagramm erstellen
fig, ax = plt.subplots(figsize=(12, 6), dpi=100)

ax.plot(local_datetimes, alt.degrees, label='Sonnenhöhe (°)', color='#e67e22', linewidth=2.5)

ax.axhline(0, color='#d35400', linestyle='--', linewidth=1.2, label='0° Auf- & Untergang')
ax.axhline(-6, color='#2980b9', linestyle=':', linewidth=1.0, label='-6° Bürgerliche Dämmerung')
ax.axhline(-12, color='#8e44ad', linestyle=':', linewidth=1.0, label='-12° Nautische Dämmerung')
ax.axhline(-18, color='#2c3e50', linestyle=':', linewidth=1.0, label='-18° Astronomische Dämmerung')

ax.fill_between(local_datetimes, alt.degrees, 0, where=(alt.degrees > 0), 
                color='#f1c40f', alpha=0.3, label='Tag (> 0°)')
ax.fill_between(local_datetimes, alt.degrees, -6, where=(alt.degrees <= 0) & (alt.degrees > -6), 
                color='#3498db', alpha=0.25)
ax.fill_between(local_datetimes, alt.degrees, -12, where=(alt.degrees <= -6) & (alt.degrees > -12), 
                color='#9b59b6', alpha=0.2)
ax.fill_between(local_datetimes, alt.degrees, -18, where=(alt.degrees <= -12) & (alt.degrees > -18), 
                color='#34495e', alpha=0.2)
ax.fill_between(local_datetimes, alt.degrees, -90, where=(alt.degrees <= -18), 
                color='#1a252f', alpha=0.35)

for time_evt in t_events:
    dt_local = time_evt.astimezone(local_tz)
    ax.axvline(dt_local, color='gray', linestyle='--', alpha=0.3, linewidth=0.8)

date_str = now_local.strftime('%d.%m.%Y')
ax.set_title(f'Sonnenverlauf & Dämmerung am {date_str} (Minga / München)', fontsize=14, fontweight='bold')
ax.set_xlabel('Ortszeit (MEZ/MESZ)', fontsize=11)
ax.set_ylabel('Höhe über dem Horizont (°)', fontsize=11)
ax.grid(True, linestyle=':', alpha=0.5)

ax.set_ylim(-30, max(45, np.ceil(alt.degrees.max() / 10) * 10))

ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M', tz=local_tz))
ax.xaxis.set_major_locator(mdates.HourLocator(interval=2, tz=local_tz))
fig.autofmt_xdate()

ax.legend(loc='upper right', frameon=True, fontsize=9)
plt.tight_layout()

output_filename = f"/var/www/html/sun/sonnenverlauf_minga.png"
plt.savefig(output_filename, dpi=300, bbox_inches='tight')
plt.close()