#!/usr/bin/env python3
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
from skyfield import almanac
from skyfield.api import load, wgs84

def main():
    eph = load('de440.bsp')
    ts = load.timescale()

    lat = 48.173333
    lon = 11.635
    elevation = 520.0
    location = wgs84.latlon(lat, lon, elevation_m=elevation)

    local_tz = ZoneInfo("Europe/Berlin")

    now_utc = datetime.now(timezone.utc).replace(microsecond=0)
    t_now = ts.from_datetime(now_utc)

    t0 = ts.from_datetime(now_utc - timedelta(days=35))
    t1 = ts.from_datetime(now_utc + timedelta(days=35))

    phase_func = almanac.moon_phases(eph)
    times, phases = almanac.find_discrete(t0, t1, phase_func)

    # Phase 2 entspricht dem Vollmond (0 = Neumond, 1 = Erstes Viertel, 2 = Vollmond, 3 = Letztes Viertel)
    full_moons = [t for t, p in zip(times, phases) if p == 2]

    past_fms = [t for t in full_moons if t.tt <= t_now.tt]
    future_fms = [t for t in full_moons if t.tt > t_now.tt]

    last_fm = past_fms[-1] if past_fms else None
    next_fm = future_fms[0] if future_fms else None

    closest_fm = min(
        full_moons,
        key=lambda t: abs((t.utc_datetime() - now_utc).total_seconds())
    ) if full_moons else None

    def format_ts(t):
        if t is None:
            return "N/A"
        dt_utc = t.utc_datetime()
        dt_local = dt_utc.astimezone(local_tz)
        return f"{dt_local.strftime('%Y-%m-%d %H:%M:%S %Z')} (UTC: {dt_utc.strftime('%H:%M:%S')})"

    print("=" * 70)
    print(" VOLLMOND-BERECHNUNG (Skyfield)")
    print("=" * 70)
    print(f"Standort:      Lat {lat} Grad, Lon {lon} Grad, {elevation} m ueber NHN")
    print(f"Aktuelle Zeit: {now_utc.astimezone(local_tz).strftime('%Y-%m-%d %H:%M:%S %Z')}")
    print("-" * 70)
    print(f"Letzter Vollmond:   {format_ts(last_fm)}")
    print(f"Naechstgelegener:   {format_ts(closest_fm)}")
    print(f"Naechster Vollmond: {format_ts(next_fm)}")
    print("=" * 70)

if __name__ == "__main__":
    main()
