#!/usr/bin/env python

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

import os.path
from os import path
import subprocess
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import fits
from astropy.table import Table
from matplotlib.colors import LogNorm

import re
import pyds9

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))

fwc_dir=root_path+'/data/FWC'
archive_dir=root_path+'/data/archive'
events_dir=root_path+'/data/processed'
events_dir_oot=root_path+'/data/processed-oot'
products_dir=root_path+'/products/sas'
ds9reg_dir=root_path+'/data/ds9reg'


create_folder(products_dir)

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

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

for obsid in files:
    obsid = os.path.basename(obsid)
    if not (obsid in good):
        continue

    work_dir = init_work_dir(obsid, products_dir=products_dir)
    os.chdir(work_dir)

    #
    # https://www.cosmos.esa.int/web/xmm-newton/sas-thread-images
    #

    attfile = get_first_file(events_dir+f'/{obsid}/*{obsid}_AttHk.ds')

    #for key in ['MOS1','MOS2','PN']:
    for key in ['MOS2']:
        evtfile = get_first_file(events_dir+f'/{obsid}/*{obsid}_E{key}*_ImagingEvts.ds')
        if not (os.path.isfile(evtfile)==True):
            continue
        fwcfile = get_first_file(fwc_dir+f'/{key}_closed_FF_2025_v1.fits')
        pimin=" ".join(emin)
        pimax=" ".join(emax)
        gti=f'EPIC_{key}_gti.fit'
        sci_clean=work_dir+f'/EPIC_{key}_filtered.fits'   # Name of the output file
        inargs     = [f'evtfile={evtfile}','withemtaglenoise=no',
                      f'fwcfile={fwcfile}','withfwcimages=yes',
                      f'gtifile={gti}',
                      f'attfile={attfile}',
                      f'pimin={pimin}',
                      f'pimax={pimax}',
                      ]
        if(key=='PN'):
            evtfile_oot = get_first_file(events_dir_oot+f'/{obsid}/*{obsid}_E{key}*_ImagingEvts.ds')
            inargs.append(f'ootfile={evtfile_oot}')
        w("eimageget", inargs).run()

        #sys.exit()
