from skyfield.api import load, Topos
from datetime import datetime, timedelta, timezone
import numpy as np
from skyfield.api import EarthSatellite

# Load satellite TLE data
def read_tle(filename):
    with open(filename, 'r') as file:
        lines = file.readlines()
    return lines[1].strip(), lines[2].strip()

# Load observer location
def read_location(filename):
    with open(filename, 'r') as file:
        lines = file.readlines()
    return float(lines[0].strip()), float(lines[1].strip())

# Compute look angles
def track_look_angles(tle1, tle2, lat, lon, start_time, end_time, output_file):
    ts = load.timescale()
    satellite = EarthSatellite(tle1, tle2, "", ts)
    observer = Topos(latitude_degrees=lat, longitude_degrees=lon)
    
    time_step = timedelta(milliseconds=50)
    current_time = start_time
    
    with open(output_file, 'w') as file:
        while current_time <= end_time:
            t = ts.utc(current_time.year, current_time.month, current_time.day,
                       current_time.hour, current_time.minute, current_time.second)
            difference = satellite - observer
            topocentric = difference.at(t)
            alt, az, _ = topocentric.altaz()
            
            file.write(f"{current_time.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]}, {az.degrees:.3f}, {alt.degrees:.3f}\n")
            #print(f"{current_time.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]}, {az.degrees:.2f}, {alt.degrees:.2f}")
            
            current_time += time_step
    print("Tracking completed.")

tle_file = 'tle.txt'
location_file = 'location.txt'
output_file = 'look_angles_ms_py.txt'

tle1, tle2 = read_tle(tle_file)
lat, lon = read_location(location_file)

start_time = datetime.now(timezone.utc)
end_time = start_time + timedelta(days=1)  # Modify as needed

print("Tracking started.")
track_look_angles(tle1, tle2, lat, lon, start_time, end_time, output_file)
