import math,sys
from datetime import datetime,timedelta,timezone
from sgp4.api import Satrec,jday
L=[l.strip() for l in open('/tmp/active.tle') if l.strip()]
def sat_of(name):
    i=[k for k,l in enumerate(L) if l.startswith(name)][0];return Satrec.twoline2rv(L[i+1],L[i+2]),L[i+1][18:32]
def ecef(sat,t):
    jd,fr=jday(t.year,t.month,t.day,t.hour,t.minute,t.second)
    e,r,v=sat.sgp4(jd,fr)
    th=math.radians((280.46061837+360.98564736629*((jd-2451545.0)+fr))%360)
    x,y,z=r;return (x*math.cos(th)+y*math.sin(th),-x*math.sin(th)+y*math.cos(th),z)
def el(p,lat,lon):
    la,lo=math.radians(lat),math.radians(lon);a=6378.137;f=1/298.257;e2=f*(2-f)
    N=a/math.sqrt(1-e2*math.sin(la)**2);o=((N)*math.cos(la)*math.cos(lo),N*math.cos(la)*math.sin(lo),N*(1-e2)*math.sin(la))
    d=[p[k]-o[k] for k in range(3)];up=(math.cos(la)*math.cos(lo),math.cos(la)*math.sin(lo),math.sin(la))
    r=math.sqrt(sum(x*x for x in d));return math.degrees(math.asin(sum(d[k]*up[k] for k in range(3))/r))
def next_pass(name,lat,lon,start,minel=0):
    sat,ep=sat_of(name);t=start
    while True:
        if el(ecef(sat,t),lat,lon)>=0:
            s=t;mx=-90
            while el(ecef(sat,t),lat,lon)>=0:
                e=el(ecef(sat,t),lat,lon);mx=max(mx,e);t+=timedelta(seconds=10)
            return s,t,mx,ep
        t+=timedelta(seconds=20)
if __name__=='__main__':
    now=datetime.now(timezone.utc)
    for lab,lat,lon in (('sv9efl',35.353333,24.456667),('ta3hx',38.4375,27.125),('yo8kgu',47.641855,26.245486)):
        s,e,m,ep=next_pass('ISS (ZARYA)',lat,lon,now)
        print(lab,s.strftime('%H:%M:%S'),e.strftime('%H:%M:%S'),'max %.1f'%m,'tle epoch',ep)
    print(now)
