from dataclasses import dataclass
from typing import Any

@dataclass
class TleData:
    catalog_id: Any = None
    classification: Any = None
    international_designator_year: Any = None
    international_designator_number: Any = None
    international_designator_piece: Any = None
    epoch_year: Any = None
    epoch_day: Any = None
    mean_motion_deriv: Any = None
    mean_motion_sec_deriv: Any = None
    drag_term: Any = None
    ephemeris_type: Any = None
    element_set_number: Any = None
    inclination: Any = None
    right_ascension: Any = None
    eccentricity: Any = None
    argument_of_perigee: Any = None
    mean_anomaly: Any = None
    mean_motion: Any = None
    revolution_number: Any = None

def parse_tle_number(text, decimal_assumed=False):
    print(text)
    negative = False
    if text[0] == "-":
        negative = True
        text = text[1:]
    if text[0] == "." or decimal_assumed:
        text = "0" + text
    if "-" in text:
        val, exp = text.split("-")
        val = float(val) * (10**-int(exp))
    elif "+" in text:
        val, exp = text.split("+")
        val = float(val) * (10**int(exp))
    else:
        val = float(text)
    if negative:
        val *= -1
    print(val)
    return val

def verify_checksum(line):
    line = line.strip()
    total = 0
    for char in line[:-1]:
        try:
            digit = int(char)
            total += digit
        except ValueError:
            if char == "-":
                total += 1
    print(total)
    return str(total)[-1] == line[-1]

def parse_tle(lines):
    data = TleData()
    if len(lines) > 2:
        l1, l2 = lines[1], lines[2]
    else:
        l1, l2 = lines
    assert verify_checksum(l1)
    assert verify_checksum(l2)
    assert l1[0] == "1"
    assert l2[0] == "2"
    l1, l2 = l1.split(), l2.split()
    assert l1[1][:-1] == l2[1]
    data.catalog_id = l1[1][:-1]
    data.classification = l1[1][-1]
    data.international_designator_year = int(l1[2][0:2])
    data.international_designator_number = int(l1[2][2:5])
    data.international_designator_piece = l1[2][5:].strip()
    data.epoch_year = int(l1[3][:2])
    data.epoch_day = float(l1[3][2:])
    data.mean_motion_deriv = parse_tle_number(l1[4])
    data.mean_motion_sec_deriv = parse_tle_number(l1[5], True)
    data.drag_term = parse_tle_number(l1[6], True)
    assert l1[7] == "0"
    data.element_set_number = int(l1[8][:-1])
    data.inclination = parse_tle_number(l2[2])
    data.right_ascension = parse_tle_number(l2[3])
    data.eccentricity = parse_tle_number(l2[4])
    data.argument_of_perigee = parse_tle_number(l2[5])
    data.mean_anomaly = parse_tle_number(l2[6])
    data.mean_motion = parse_tle_number(l2[7][:11])
    data.revolution_number = parse_tle_number(l2[7][11:-1])
    return data

if __name__ == "__main__":
    with open("../data/iss_tle.txt") as f:
        tle = f.readlines()
    print(parse_tle(tle))