# from sys import argv
# from tools import process_calc_bore_sight
# if __name__ == '__main__':
#     if len(argv) == 2:
#         nProcess = int(argv[1])
#     else:
#         nProcess = 20
# process_calc_bore_sight(nProcess)

# from sys import argv
# from tools import gen_bore_sight_lut
# if __name__ == '__main__':
#     if len(argv) == 2:
#         nProcess = int(argv[1])
#     else:
#         nProcess = 20
# gen_bore_sight_lut()

from pathlib import Path
from datetime import datetime, timedelta
from os import system
import pickle
from re import sub
from tools import to_datetime
root_dir = Path('/GNSSRO_data2/xinjiaz/data_GPSRO/TACC/level1a/podCrx/')
# root_dir = Path('/GNSSRO_data2/xinjiaz/data_GPSRO/UCAR/cosmic2/level1a/podCrx/')
# process_dates = [datetime(2025, 1, 1) + timedelta(days=x) for x in range(575)]
# process_dates = [datetime(2025, 6, 23) + timedelta(days=x) for x in range(3)]
process_dates = [datetime(2026,6, 19)]
for dt in process_dates:
    print(f'{datetime.now():%H:%M:%S} - Processing {dt:%Y-%m-%d}',flush=True)
    dcode = {}
    ctime = {}
    ptime = {}
    tarfiles = list((root_dir / f'{dt:%Y/%j}').glob('*_crx.gz'))
    for tarfile in (root_dir / f'{dt:%Y/%j}').glob('*_crx.gz'):
        tar_out = Path('temp') / (tarfile.stem[:-4] + '.crx')
        system('gunzip -c ' + tarfile.as_posix() + '> ' + tar_out.as_posix())
        system('./crx2rnx ' + tar_out.as_posix())
        system('rm ' + tar_out.as_posix())
        tar_out = tar_out.with_suffix('.rnx')
        is_head = True
        count = 0
        sat_append = False
        leo = sub(r'podCrx_\d{4}\.\d{3}\.00(\d)\.\d\d\.\d\d', r'\1' ,tar_out.stem)
        for line in open(tar_out, 'r'):
            if is_head:
                if 'END OF HEADER' in line:
                    is_head = False
                continue
            if sat_append:
                sats = [line[32 + 3 * x:35 + 3 * x] for x in range(min(12, sat_num))][::-1] + sats
                if sat_num > 12:
                    sat_num -= 12
                else:
                    sat_append = False
            elif count == 0:
                dt_now = to_datetime(('20' + line[1:]).split())
                sat_num = int(line[29:32])
                sats = [line[32 + 3 * x:35 + 3 * x] for x in range(min(12, sat_num))][::-1]
                count = sat_num * 2
                if sat_num > 12:
                    sat_num -= 12
                    sat_append = True
            elif count % 2 == 0:
                count -= 1
                gtmp = len([line[ii:ii + 14] for ii in range(0, len(line) - 1, 16)]) - 3
            else:
                count -= 1
                gsat = sats.pop()
                if gsat == 'G13' or gsat == 'G20':
                    gsat += '-C2E'+leo
                else:
                    continue
                if gsat not in dcode:
                    dcode[gsat] = gtmp
                else:
                    dcode[gsat] |= gtmp
                if gtmp == 1:
                    if gsat not in ctime:
                        ctime[gsat] = [dt_now, dt_now]
                    else:
                        ctime[gsat] = [min(ctime[gsat][0], dt_now), max(ctime[gsat][1], dt_now)]
                elif gtmp == 2:
                    if gsat not in ptime:
                        ptime[gsat] = [dt_now, dt_now]
                    else:
                        ptime[gsat] = [min(ptime[gsat][0], dt_now), max(ptime[gsat][1], dt_now)]
                else:
                    raise LookupError(f'Cound not recognize {gtmp}')
        system('rm ' + tar_out.as_posix())
    dcode = dict(sorted(dcode.items()))
    # print('    C:', end='',flush=True)
    # for ss,vv in dcode.items():
    #     if vv==1:
    #         print(ss, end=' ',flush=True)
    # print('',flush=True)
    # print('    P:', end='',flush=True)
    # for ss,vv in dcode.items():
    #     if vv==2:
    #         print(ss, end=' ',flush=True)
    # print('',flush=True)
    # print('  C/P:', end='',flush=True)
    # for ss,vv in dcode.items():
    #     if vv==3:
    #         print(ss, end=' ',flush=True)
    # print('',flush=True)
    # print('    X:', end='',flush=True)
    # for ss,vv in dcode.items():
    #     if vv not in [1,2,3]:
    #         print(ss, end=' ',flush=True)
    # print('',flush=True)
    print('C:', flush=True)
    for ss,vv in ctime.items():
        print(f' {ss}: {vv[0]:%Y-%m-%d %H:%M:%S} - {vv[1]:%Y-%m-%d %H:%M:%S}', flush=True)
    print('P:', flush=True)
    for ss,vv in ptime.items():
        print(f' {ss}: {vv[0]:%Y-%m-%d %H:%M:%S} - {vv[1]:%Y-%m-%d %H:%M:%S}', flush=True)
    # with open(Path('p01_podCode') / f'podCode_{dt:%Y-%m-%d}_leo.pkl', 'wb') as fid:
    #     pickle.dump(dcode, fid)

ptimes = {'G02':[None]*6,'G13':[None]*6,'G16':[None]*6,'G19':[None]*6,'G20':[None]*6,'G21':[None]*6,'G22':[None]*6}
ptimes['G13']=[datetime(2026,6,19,8,10), datetime(2026,6,19,8,50), None, datetime(2026,6,19,7,40), datetime(2026,6,19,7,40), datetime(2026,6,19,8, 2)]
ptimes['G20']=[datetime(2026,6,19,8,15), datetime(2026,6,19,9, 4), None, datetime(2026,6,19,6,47), datetime(2026,6,19,7, 0), datetime(2026,6,19,8,30)]
ptimes['G21']=[datetime(2025,6,23,4, 0), datetime(2025,6,23,4,20), None, datetime(2025,6,25,3,45), datetime(2025,6,23,5,30), datetime(2025,6,23,5,45)]
with open(Path('p01_podCode') / f'podCode_Psats.pkl', 'wb') as fid:
    pickle.dump(ptimes, fid)
