#!/usr/bin/env python

from pysas.wrapper import Wrapper as w
import os, sys
from os.path import dirname
import inspect
import glob

import arches
from arches.utils import *
from arches.config import *

root_path=dirname(dirname(dirname(inspect.getfile(arches))))
print("Arches root path: {}".format(root_path))

archive_dir=root_path+'/data/archive'
events_dir=root_path+'/data/processed-oot'
#products_dir=root_path+'/products'

create_folder(events_dir)

inargs = ['--version']
t = w('sasver', inargs)
t.run()

files = glob.glob(archive_dir+'/0862*')

for obsid in files:
    obsid = os.path.basename(obsid)
    
    local_ccf=f'{events_dir}/{obsid}/ccf.cif'
    work_dir=f'{events_dir}/{obsid}'

    #inargs = [f'odfid={obsid}',f'workdir={work_dir}']
    #w('startsas', inargs).run()

    os.environ['SAS_ODF'] = f'{archive_dir}/{obsid}/odf'

    create_folder(work_dir)

    os.chdir(work_dir)

    if not os.path.exists(local_ccf):
        w('cifbuild', []).run()
    else:
        print("*** Skip cifbuild, SAS_CCF = {}".format(local_ccf))
    
    os.environ['SAS_CCF'] = local_ccf

    print("Set SAS_CCF = {}".format(os.environ['SAS_CCF']))

    w('sasver', []).run() # print info

    sasfiles = glob.glob(work_dir+'/*SUM.SAS')
    if(sasfiles):
        print("*** Skip odfingest ***")
    else:
        w('odfingest', []).run()
        sasfiles = glob.glob(work_dir+'/*SUM.SAS') # search files again

    os.environ['SAS_ODF'] = sasfiles[0]

    w('sasver', []).run() # print info

    search_str=f'{work_dir}/????_{obsid}_EPN_S???_ImagingEvts.ds'
    epfiles = glob.glob(search_str)
    if not (epfiles):
        print('*** Running epproc')
        w('epproc', ['withoutoftime=true',]).run()
    else:
        print('*** Skipping epproc')



    
