import requests
from datetime import datetime
import re

def fetch_leap_second_data():
    """从IERS网站获取闰秒数据"""
    url = "https://hpiers.obspm.fr/iers/bul/bulc/Leap_Second.dat"
    try:
        response = requests.get(url)
        response.raise_for_status()
        return response.text
    except requests.RequestException as e:
        print(f"获取数据失败: {e}")
        return None

def parse_leap_second_data(data):
    """解析闰秒数据"""
    leap_seconds = []
    
    for line in data.split('\n'):
        # 跳过注释行和空行
        if line.startswith('#') or not line.strip():
            continue
            
        # 解析数据行: MJD Date TAI-UTC
        parts = line.split()
        if len(parts) >= 3:
            try:
                mjd = float(parts[0])
                date_str = f"{parts[1]} {parts[2]} {parts[3]}"
                tai_utc = int(parts[4])
                
                # 解析日期
                date_obj = datetime.strptime(date_str, "%d %m %Y")
                
                leap_seconds.append({
                    'mjd': mjd,
                    'date': date_obj,
                    'tai_utc': tai_utc,
                    'gps_utc': tai_utc - 19  # GPS = TAI - 19秒
                })
            except (ValueError, IndexError):
                continue
    
    return leap_seconds

def display_leap_seconds(leap_seconds):
    """显示闰秒信息"""
    print("闰秒数据解析结果:")
    print("=" * 80)
    print(f"{'MJD':<10} {'日期':<12} {'TAI-UTC':<8} {'GPS-UTC':<8}")
    print("-" * 80)
    
    for entry in leap_seconds:
        print(f"{entry['mjd']:<10.1f} {entry['date'].strftime('%Y-%m-%d'):<12} "
              f"{entry['tai_utc']:<8} {entry['gps_utc']:<8}")
    
    print("\n" + "=" * 80)
    print("说明:")
    print("- TAI-UTC: 国际原子时与协调世界时的差值")
    print("- GPS-UTC: GPS时间与协调世界时的差值 (GPS = TAI - 19秒)")
    print("- 正值表示TAI/GPS比UTC快")
    
    # 显示最新的闰秒信息
    if leap_seconds:
        latest = leap_seconds[-1]
        print(f"\n最新闰秒信息 (截至 {latest['date'].strftime('%Y-%m-%d')}):")
        print(f"TAI-UTC: {latest['tai_utc']} 秒")
        print(f"GPS-UTC: {latest['gps_utc']} 秒")

def main():
    """主函数"""
    print("正在从IERS获取闰秒数据...")
    
    # 获取数据
    data = fetch_leap_second_data()
    if not data:
        print("无法获取数据，使用提供的示例数据...")
        # 使用提供的示例数据
        data = """# Value of TAI-UTC in second valid beetween the initial value until # the epoch given on the next line. The last line reads that NO # leap second was introduced since the corresponding date # Updated through IERS Bulletin 69 issued in January 2025 # # # File expires on 28 December 2025 # # # MJD Date TAI-UTC (s) # day month year # --- -------------- ------ # 41317.0 1 1 1972 10 41499.0 1 7 1972 11 41683.0 1 1 1973 12 42048.0 1 1 1974 13 42413.0 1 1 1975 14 42778.0 1 1 1976 15 43144.0 1 1 1977 16 43509.0 1 1 1978 17 43874.0 1 1 1979 18 44239.0 1 1 1980 19 44786.0 1 7 1981 20 45151.0 1 7 1982 21 45516.0 1 7 1983 22 46247.0 1 7 1985 23 47161.0 1 1 1988 24 47892.0 1 1 1990 25 48257.0 1 1 1991 26 48804.0 1 7 1992 27 49169.0 1 7 1993 28 49534.0 1 7 1994 29 50083.0 1 1 1996 30 50630.0 1 7 1997 31 51179.0 1 1 1999 32 53736.0 1 1 2006 33 54832.0 1 1 2009 34 56109.0 1 7 2012 35 57204.0 1 7 2015 36 57754.0 1 1 2017 37"""
    
    # 解析数据
    leap_seconds = parse_leap_second_data(data)
    
    if leap_seconds:
        display_leap_seconds(leap_seconds)
    else:
        print("解析数据失败")

if __name__ == "__main__":
    main()
