
import re
from datetime import datetime

__authors__ = ["Ming Chen"]
__license__ = "Public Domain"
__maintainer__ = "Ming Chen"
__email__ = "ming.chen@noaa.gov"
__date__  = "April 1, 2026"

'''
#####################################################################
# 
# extract_att.py
#
# Purpose:
# This python script is used to extract the leo attitude data of a specific
# range of epoches from the input attitude file and to generate a new attitude file
##
# History:  
#       Created by: Ming Chen 2026/04/01
#                   ming.chen@noaa.gov
# 
# Usage: 
#
#
#####################################################################

'''

# =========================
# Parse "tim" line
# =========================
def parse_tim(line):
    p = line.split()
    return datetime(
        int(p[1]), int(p[2]), int(p[3]),
        int(p[4]), int(p[5]), int(float(p[6]))
    )

# =========================
# Read header
# =========================
def read_header(f):
    header = []
    first_data_line = None

    while True:
        line = f.readline()
        if not line:
            break

        if line.startswith("tim"):
            first_data_line = line
            break

        header.append(line.rstrip("\n"))

    return header, first_data_line


# =========================
# Epoch generator
# =========================
def epoch_generator(f, first_line):

    line = first_line

    while line:
        if not line.startswith("tim"):
            line = f.readline()
            continue

        block = [line.rstrip("\n")]
        dt = parse_tim(line)

        while True:
            pos = f.readline()
            if not pos or pos.startswith("tim"):
                yield dt, block
                line = pos
                break

            block.append(pos.rstrip("\n"))


# =========================
# Update header times
# =========================
def update_header(header, first_dt, last_dt):

    new_header = []

    for line in header:
        if line.startswith("+first____"):
            line = (
                f"+first____ {first_dt.year:4d} {first_dt.month:2d} {first_dt.day:2d} "
                f"{first_dt.hour:2d} {first_dt.minute:2d} {first_dt.second:2d}.0000000"
            )
        elif line.startswith("+last_____"):
            line = (
                f"+last_____ {last_dt.year:4d} {last_dt.month:2d} {last_dt.day:2d} "
                f"{last_dt.hour:2d} {last_dt.minute:2d} {last_dt.second:2d}.0000000"
            )

        new_header.append(line)

    return new_header


# =========================
# MAIN FUNCTION
# =========================
def extract_time_range(infile, outfile, start_dt, end_dt):

    selected = []

    with open(infile, "r") as f:
        header, first_line = read_header(f)

        for dt, block in epoch_generator(f, first_line):
            if start_dt <= dt <= end_dt:
                selected.append((dt, block))

    if not selected:
        print("No data in selected time range.")
        return

    # update header
    header = update_header(header, selected[0][0], selected[-1][0])

    # write output
    with open(outfile, "w") as f:
        for line in header:
            f.write(line + "\n")

        for _, block in selected:
            for line in block:
                f.write(line + "\n")



# ----------------------------------------------------------------------
# Argument parsing
# ----------------------------------------------------------------------
def parse_args():
    import argparse
    parser = argparse.ArgumentParser(
        description="Main Program arguments"
    )
   
    parser.add_argument("input", type=str,  help="attitude input")
    parser.add_argument("output", type=str,  help="output")
    parser.add_argument("-start", "--start-time", type=str,  help="%Y%m%dT%H%M%S")
    parser.add_argument("-end", "--end-time", type=str,  help="%Y%m%dT%H%M%S")
    parser.add_argument("-v","--verbose", action='store_true',  help="print info for debug")


    return parser.parse_args()

    
if __name__ == "__main__":
    # python extract_att.py /data2/mchen36/POD_DATA/cosmic2/LEOPOD/leoAtt/2026.108/C211_20260418T132000.att test.out -start 20260418T122000 -end 20260418T132000
    args = parse_args()
    t_start = args.start_time
    t_end = args.end_time
    tstart = datetime.strptime(t_start, "%Y%m%dT%H%M%S")
    tend =  datetime.strptime(t_end, "%Y%m%dT%H%M%S")

    input_file = args.input ; output_file = args.output
    
    verbose = args.verbose

    print( tstart, tend)
    extract_time_range(input_file, output_file, tstart, tend)
  
