import astropy.io.fits as pyfits
import os
import numpy as np
import sys

def create_header(extension):
    extension.header['TELESCOP'] = 'THESEUS'
    extension.header['EXTNAME'] = 'SPECRESP'
    extension.header['INSTRUME'] = 'XGIS'
    extension.header['FILTER'] = 'NONE'
    extension.header['HDUCLASS'] = 'OGIP'
    extension.header['HDUCLAS1'] = 'RESPONSE'
    extension.header['HDUCLAS2'] = 'SPECRESP'
    extension.header['HDUVERS'] = '1.1.0'
    # obsolete (for old software)
    extension.header['ARFVERSN'] = '1992A'
    extension.header['HDUVERS1'] = '1.0.0'
    extension.header['HDUVERS2'] = '1.1.0'
    extension.header['COMMENT'] = "Alfonso Pisapia"

def arf_file(energy_filt, ratio_X_filt, ratio_S_filt, theta, phi):
    try:
        # Creazione di "Null" primary array
        primary_hdu = pyfits.PrimaryHDU()

        # Creazione di BinTableHDU per EVENTI X
        bin_tableX_hdu = pyfits.BinTableHDU.from_columns([
            pyfits.Column(name='ENERG_LO', format='1E', unit='keV', array=energy_filt[:-1]),
            pyfits.Column(name='ENERG_HI', format='1E', unit='keV', array=energy_filt[1:]),
            pyfits.Column(name='SPECRESP', format='1E', unit='cm**2', array=ratio_X_filt),
        ])
        create_header(bin_tableX_hdu)  # Aggiunta header comune per gli eventi X

        # Creazione di BinTableHDU per EVENTI S
        bin_tableS_hdu = pyfits.BinTableHDU.from_columns([
            pyfits.Column(name='ENERG_LO', format='1E', unit='keV', array=energy_filt[:-1]),
            pyfits.Column(name='ENERG_HI', format='1E', unit='keV', array=energy_filt[1:]),
            pyfits.Column(name='SPECRESP', format='1E', unit='cm**2', array=ratio_S_filt),
        ])
        create_header(bin_tableS_hdu)  # Aggiunta header comune per gli eventi S



        # Creazione di HDUList e scrittura del file FITS
        hdulX = pyfits.HDUList([primary_hdu, bin_tableX_hdu])
        hdulS = pyfits.HDUList([primary_hdu, bin_tableS_hdu])

        output_dir = "/home/alfonso/Scrivania/THESEUS/xgis_m7-main/arf"
        
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)
            
        output_X = os.path.join(output_dir, f"XaeFF_{theta}_{phi}.arf")
        output_S = os.path.join(output_dir, f"SaeFF_{theta}_{phi}.arf")

        hdulX.writeto(output_X, overwrite=True)
        hdulS.writeto(output_S, overwrite=True)

        print("File .arf creati correttamente.")
    except Exception as e:
        print(f"Errore durante la creazione del file .arf: {e}")
