#!/usr/bin/env python
import os, sys, glob, subprocess, shutil
from datetime import datetime, timedelta
import re, string
import numpy as np
from satellite_info import env_paths, sat_ant_info

from ucar2umd_att import UCAR2UMD_ATT
from utility import str2date, leofile_time_range
from ucar_gnssro_data import local_ucar_filelist

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

'''
#####################################################################
# 
# ucar2umd_att_rt.py
#
# Purpose:
# This Python driver script merges UCAR sub-daily LEO attitude data files
# into a unified file over a user-defined epoch range to support
# real-time POD processing with the BERNESE software package.
##
# History:  
#       Created by: Ming Chen 2026/04/24
#                   ming.chen@noaa.gov
# 
# Usage: python  ucar2umd_att_rt.py  --verbose mission satidx sdate edate
#
# Args:  mission[cosmic2, spire, cosmic1] satidx 
#        start-date[yyyyddd|yyyymndd] [end-date] --window-hours [1-12]
#
#####################################################################

'''
def umdrepo_att_filelist(mission, satidx,  sdate, **kwargs):      
    # Check if required environment variables are set

    umd_repo = kwargs.get('umd_repo','')
    satinfo = sat_ant_info(mission, satidx)
    if satinfo == None:return None
    satsvn =  satinfo['satsvn'] ; satname = satinfo['satname'] 
    year = sdate.strftime('%Y') 
    jday = sdate.strftime('%j')
    #leoAtt_path =  os.path.join(umd_repo, mission,'level1a', 'leoAtt', year, jday)
    leoAtt_path =  os.path.join(umd_repo, year, jday)
    fnames = 'leoAtt_{}.{}.{}.*'.format(year, jday, satsvn)
    filelist = glob.glob(leoAtt_path+'/'+fnames+'_txt', recursive=False)       
    return filelist 

def umdatt_filepath(mission, pdate):
    umddir  = os.getenv('umd_data')
    year = pdate.strftime('%Y') ; jday = pdate.strftime('%j')
    yday = f'{year}.{jday}' 
    umdLeoAtt_Path =  os.path.join(umddir, mission, 'leoAtt', yday)
    
    return umdLeoAtt_Path

def umdatt_filename(mission, satidx, tstart, tend):
    satinfo = sat_ant_info(mission, satidx)
    if satinfo == None:return None
    satsvn =  satinfo['satsvn'] ; satname = satinfo['satname'] 
    t1 = tstart.strftime('%Y%m%dT%H%M%S')
    t2 = tend.strftime('%Y%m%dT%H%M%S')
    outfile = f"{mission}_{t1}_{t2}_{satsvn}.att"
    return outfile


def ucar2umd_att_session(mission, satidx, tstart, tend, **kwargs):      
    
    alpha=list(string.ascii_uppercase)
    verbose = kwargs.get('verbose') 
    umd_repo = kwargs.get('umd_repo','')
    grace_hours = kwargs.get('grace_hours',3)
    if (verbose == None): 
      verbose = os.environ['_VERBOSE_'].lower() in ('true', '1','yes')
    overwrite = kwargs.get('overwrite') 
    if (overwrite == None): 
      overwrite = os.environ['_OVERWRITE_'].lower() in ('true', '1','yes')
   
    satinfo = sat_ant_info(mission, satidx)
    if satinfo == None: return
    satsvn =  satinfo['satsvn'] ; satname = satinfo['satname'] 
    

    dt = timedelta(hours=grace_hours)
    ndays = (tend - tstart + dt + dt).days
    sdate = (tstart - dt).strftime('%Y%m%d') ; sdate = datetime.strptime(sdate,'%Y%m%d')
    edate = (tend + dt).strftime('%Y%m%d') ; edate = datetime.strptime(edate,'%Y%m%d')
    print(sdate, edate)
    flists=[]
    while sdate <= edate:
       year = sdate.strftime('%Y') 
       jday = sdate.strftime('%j')
       yday=f'{year}.{jday}'
       datestr = sdate.strftime('%Y%m%d')

       if umd_repo.strip():
          filelist =  umdrepo_att_filelist(mission, satidx,  sdate, umd_repo = umd_repo)
       else:
          filelist =  local_ucar_filelist(mission, 'leoAtt', datestr, svn=satsvn)
       flists.extend(filelist)
       sdate = sdate + timedelta(days=1)  
    filelist = sorted(flists)

    if len(filelist) < 1: return None
     
    umd = UCAR2UMD_ATT(mission=mission)
    n = 0
    for f in filelist:
        rr=leofile_time_range(f)
        r1 = datetime.strptime(rr[0],'%Y%m%dT%H:%M:%S.%f')
        r2 = datetime.strptime(rr[1],'%Y%m%dT%H:%M:%S.%f')
        #r1 = rr[0] ; r2 = rr[1]
        if  rr[0] == None : continue
        if  r1 > tend or r2 < tstart :  continue
        #print(f)
        _, basename = os.path.split(os.path.abspath(f))
        umd.add_rinex(f, verbose=verbose)
        n = n + 1

    umdLeoAtt =  umdatt_filepath(mission, tend)
    outfile = umdatt_filename(mission, satidx, tstart, tend)
    if n != 0:  
      os.makedirs(umdLeoAtt, exist_ok=True)
      fileout = os.path.join(umdLeoAtt,  outfile) 
      if os.path.exists(fileout): 
         print('{} already existed, rewrite'.format(fileout))
      t1 = tstart.strftime('%Y%m%dT%H%M%S')
      t2 = tend.strftime('%Y%m%dT%H%M%S')
      print('time range {} {} , valid ucars files {}'.format(t1, t2, n))
 
      leoprn = 923 + satidx - 1 ; leotag = 'CHACC{:3d}'.format(leoprn)
      #leoprn = 923 ; leotag = 'CHACC{:3d}'.format(leoprn)
      #umd.write_rinex(outfile=fileout, verbose = True )  
      umd.write_rinex(outfile=fileout, satellite=leotag, verbose = True )

    else : 
      print( "no LeoAtt files found...")
      msg = '{} {} leoAtt_*{}  {}'.format(umd_repo, mission, satsvn,  datestr)
      print( msg) 
      return False

def ucar2umd_att_rt(mission, tstart, tend, satidx=-1,  **kwargs):      
    umd_repo = kwargs.get('umd_repo','')
    leoinfo = sat_ant_info(mission)
    nsat = leoinfo["nsats"]
    leosats = [i+1 for i in range(nsat)]
    if satidx > 0: leosats = [satidx]   

  
    for satidx in leosats:
        ucar2umd_att_session(mission, satidx, tstart, tend, umd_repo=umd_repo)
            

# ----------------------------------------------------------------------
# Argument parsing
# ----------------------------------------------------------------------
def parse_args():
    import argparse
    parser = argparse.ArgumentParser(
        description="Main Program arguments"
    )
   
    parser.add_argument("-t","--datetime", help = "%Y-%m-%dT%H:%M:%S")
    parser.add_argument("--window-minutes", type=float, default=60.0, help="Override minutes from YAML")
    parser.add_argument("--grace-minutes", type=float, default=0.0, help="Override grace from YAML")
    parser.add_argument("--workers", type=int, default=4)
    parser.add_argument("--dry-run", action="store_true")
    parser.add_argument("mission", type=str,  help="cosmic1 or cosmic2")
    parser.add_argument("satidx", type=int,  help="cosmic2 satidx 1-6")
    parser.add_argument("--umd-repo",  type=str, default='', help="path to umd local ucar data repository"  )
    parser.add_argument("-ucar","--ucar-data-home",type=str,  help="Local UCAR data home path "  )
    parser.add_argument("-umd","--umd-data-home",  type=str,  help="UMD data home path "  )
    parser.add_argument("-util","--utility-home",  type=str,  help="POD utility home path "  )
    parser.add_argument("-v","--verbose", action='store_true',  help="print info for debug")


    return parser.parse_args()

    
if __name__ == "__main__":
    
    # example
    # python ucar2umd_att_rt.py cosmic2 2  -t "2026-04-05T03:00:00" --umd-repo '/data2/xinjiaz/data_GPSRO/UCAR'
   
    args = parse_args()
    ddt = datetime.strptime(args.datetime, "%Y-%m-%dT%H:%M:%S")

    # Time window
    window_minutes = args.window_minutes
    grace_minutes = args.grace_minutes 
    umd_repo = args.umd_repo

    total_minutes = window_minutes + grace_minutes
    if total_minutes < 0:
       t_start = ddt + timedelta(minutes=total_minutes)
       t_end   = ddt
    else:
       t_start = ddt ; t_end   = ddt + timedelta(minutes=total_minutes)

    tstart = t_start.strftime("%Y%m%dT%H%M%S")
    tend = t_end.strftime("%Y%m%dT%H%M%S")
    mission = args.mission ; satidx = args.satidx 
    
    verbose = args.verbose

    print(satidx, tstart, tend)
    ucar2umd_att_rt(mission, satidx, t_start,t_end, verbose=verbose, umd_repo =umd_repo)


