#! /usr/bin/python3
import datetime
from skyfield.api import load
from skyfield.framelib import itrs

# 1. Setup skyfield (Benötigt Installation: pip install skyfield)
print("Lade Ephemeriden...")
eph = load('de421.bsp') # Kompaktes, präzises JPL-Modell
ts = load.timescale()
sun = eph['sun']
earth = eph['earth']

# 2. Zeitbereich definieren (Das ganze Jahr 2026, stündlich)
START_YEAR = 2026
start_date = datetime.datetime(START_YEAR, 1, 1, 0, 0, 0, tzinfo=datetime.timezone.utc)
end_date = datetime.datetime(START_YEAR + 1, 1, 1, 0, 0, 0, tzinfo=datetime.timezone.utc)

OUTPUT_FILE = f"NauticalAlmanac_Sun_{START_YEAR}.tex"

print(f"Berechne Daten für {START_YEAR}...")

latex_content = r"""\documentclass{article}
\usepackage[a4paper,margin=1cm]{geometry}
\usepackage{booktabs}
\usepackage{longtable}
\usepackage{siunitx} % Für saubere Ausrichtung von Dezimalzahlen

\title{Nautical Almanac: Sonne 2026 (Stündlich)}
\author{Generiert via Python/Skyfield}
\date{\today}

\begin{document}
\maketitle

\setlength{\LTleft}{-20pt} % Tabelle etwas nach links rücken

\begin{longtable}{@{}l c r r@{}}
\caption{Greenwich Hour Angle (GHA) und Deklination (Dec) der Sonne}\\
\toprule
\textbf{UT} & \textbf{Datum} & \multicolumn{1}{c}{\textbf{SUN}} & \multicolumn{1}{c}{\textbf{SUN}} \\
\cmidrule(lr){3-4}
\textbf{h} & \textbf{d} & \multicolumn{1}{c}{\textbf{GHA}} & \multicolumn{1}{c}{\textbf{Dec}} \\
& & \multicolumn{1}{c}{$^\circ \quad ' .$} & \multicolumn{1}{c}{[N/S] $^\circ \quad ' .$} \\
\midrule
\endfirsthead

\toprule
\textbf{UT} & \textbf{Datum} & \multicolumn{1}{c}{\textbf{SUN GHA}} & \multicolumn{1}{c}{\textbf{SUN Dec}} \\
\midrule
\endhead

\bottomrule
\multicolumn{4}{r}{Fortsetzung auf nächster Seite...} \\
\endfoot
\bottomrule
\endlastfoot
"""

current_time = start_date
last_date_str = ""

while current_time < end_date:
    t = ts.from_datetime(current_time)
    
    # Position berechnen (Scheinbar, bezogen auf das terrestrische System itrs)
    # itrs gibt uns direkt GHA-ähnliche Längen und Dec-ähnliche Breiten
    astrometric = earth.at(t).observe(sun).apparent()
    position_itrs = astrometric.frame_latlon(itrs)
    lat, lon, distance = position_itrs
    
    # 3. Deklination berechnen & formatieren (z.B. "N23 17.2")
    dec_deg_raw = lat.degrees
    sign_dec = 'N' if dec_deg_raw >= 0 else 'S'
    abs_dec = abs(dec_deg_raw)
    dec_whole_deg = int(abs_dec)
    dec_min = (abs_dec - dec_whole_deg) * 60
    
    # Nautical Almanac zeigt Vorzeichen/Grad oft nur bei 00h oder Datumswechsel.
    # Zur Vereinfachung schreiben wir es hier immer voll, wie in einem Rohdaten-Almanach.
    # Format: SignDeg Min.Tenth (z.B. N12 04.5)
    dec_str = f"{sign_dec}{dec_whole_deg:02d} {dec_min:04.1f}"

    # 4. GHA berechnen & formatieren (z.B. "179 54.6")
    # itrs-Länge ist East-positiv. GHA ist West-positiv (0-360).
    # GHA = -Länge (modulo 360)
    gha_deg_raw = (-lon.degrees) % 360
    gha_whole_deg = int(gha_deg_raw)
    gha_min = (gha_deg_raw - gha_whole_deg) * 60
    
    # Format: Deg Min.Tenth (z.B. 179 54.6)
    gha_str = f"{gha_whole_deg:3d} {gha_min:04.1f}"

    # 5. LaTeX-Zeile erstellen
    hour_str = f"{current_time.hour:02d}"
    date_str = current_time.strftime("%Y-%m-%d")
    
    # Datum nur in die erste Zeile eines neuen Tages schreiben
    display_date = date_str if date_str != last_date_str else ""
    
    latex_row = f"{hour_str} & {display_date} & {gha_str} & {dec_str} \\\\\n"
    latex_content += latex_row
    
    # Trennlinie nach jedem Tag
    if current_time.hour == 23:
        latex_content += r"\midrule" + "\n"

    last_date_str = date_str
    current_time += datetime.timedelta(hours=1)

latex_content += r"""\end{longtable}
\end{document}
"""

# 6. Datei speichern
print(f"Speichere LaTeX-Datei: {OUTPUT_FILE}")
with open(OUTPUT_FILE, 'w', encoding='utf-8') as f:
    f.write(latex_content)

print("Fertig.")
