#!/usr/bin/env python3
from datetime import datetime, timedelta, timezone
import math
import ephem


def get_moon_pos(lat, lon, elevation, dt):
    observer = ephem.Observer()
    observer.lat = str(lat)
    observer.lon = str(lon)
    observer.elevation = elevation
    
    # Strip tzinfo to ensure naive UTC compatibility with PyEphem
    dt_utc_naive = dt.astimezone(timezone.utc).replace(tzinfo=None)
    observer.date = dt_utc_naive

    moon = ephem.Moon()
    moon.compute(observer)
    
    az_deg = math.degrees(float(moon.az))
    alt_deg = math.degrees(float(moon.alt))
    return az_deg, alt_deg, str(moon.az), str(moon.alt)


def main():
    locations = [
        {"name": "Gaggers", "lat": "48.333333", "lon": "11.250000", "elev": 500},
        {"name": "Minga",   "lat": "48.173333", "lon": "11.635000", "elev": 515},
    ]

    now = datetime.now(timezone.utc)
    last_hour = now.replace(minute=0, second=0, microsecond=0)
    
    time_points = [
        ("Letzte volle Std.", last_hour),
        ("Viertel Std.",       last_hour + timedelta(minutes=15)),
        ("Halbe Std.",         last_hour + timedelta(minutes=30)),
        ("Dreiviertel Std.",   last_hour + timedelta(minutes=45)),   
        ("Naechste volle Std.", last_hour + timedelta(hours=1)),
    ]

    header = f"| {'Standort':<8} | {'Uhrzeit (UTC)':<19} | {'Azimut (Az)':<26} | {'Hoehe (Alt)':<26} |"
    divider = "+" + "-" * (len(header) - 2) + "+"

    print(divider)
    print(header)
    print(divider)

    for loc in locations:
        for label, dt in time_points:
            az, alt, a_str, t_str = get_moon_pos(loc["lat"], loc["lon"], loc["elev"], dt)
            time_str = dt.strftime("%Y-%m-%d %H:%M:%S")
            print(
                f"| {loc['name']:<8} | {time_str:<19} | {az:>9.5f} Grad {a_str:>11} | {alt:>9.5f} Grad {t_str:>11} |"
            )
        print(divider)


if __name__ == "__main__":
    main()
