#!/usr/bin/python3
import urllib.request
from datetime import datetime

# Stabile USNO-Spiegel-URL für das IERS-Bulletin (finals2000A)
IERS_URL = "https://datacenter.iers.org/data/csv/finals2000A.all.csv"
# Alternative direkte USNO-Quelle:
USNO_FALLBACK = "https://maia.usno.navy.mil/ser7/finals2000A.all"

def get_delta_t_from_usno(target_date: datetime) -> float:
    """
    Liest Delta T (in Sekunden) für ein beliebiges Datum direkt vom USNO-Server aus.
    """
    url = "https://maia.usno.navy.mil/ser7/finals2000A.all"
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)'}
    
    req = urllib.request.Request(url, headers=headers)
    
    with urllib.request.urlopen(req) as response:
        lines = response.read().decode('utf-8', errors='ignore').splitlines()

    target_yy = target_date.year % 100
    target_mm = target_date.month
    target_dd = target_date.day

    for line in lines:
        if len(line) < 64:
            continue

        try:
            # Feste Spalten im USNO-Format (YYMMDD):
            yy = int(line[0:2])
            mm = int(line[2:4])
            dd = int(line[4:6])

            if yy == target_yy and mm == target_mm and dd == target_dd:
                # Delta T Spalte (Zeichen 58 bis 65)
                delta_t_str = line[57:65].strip()
                if delta_t_str:
                    return float(delta_t_str)
        except ValueError:
            continue

    raise ValueError(f"Keine Daten für {target_date.strftime('%Y-%m-%d')} gefunden.")

if __name__ == "__main__":
    test_datum = datetime(2026, 7, 23)
    
    try:
        dt = get_delta_t_from_usno(test_datum)
        print(f"Datum:   {test_datum.strftime('%Y-%m-%d')}")
        print(f"Delta T: {dt:.4f} Sekunden")
    except Exception as e:
        print(f"Fehler beim Abruf: {e}")
