form astropy.io import fits
min_exp = 0.001
max_exp = 30


def make_TW_flats(binning=1, filt=1, target_counts_pixel=50000, nit=0, when, season):

    # relative time rate of change of sky surface brightness (s^-1)
    k = 0.091/60
    if when == 'twilight':
        k = -k
    elif when == 'dawn':
        pass
    else:
        log.warning('Invalid input')
        sys.exit(1)

    # durata alba astronomica normalizzata a equinozio primavera +-30
    if season == 'winter':
        tau = 1.33
    elif season == 'summer':
        tau = 1.91
    elif season == 'sping' or 'autumn':
        tau = 1.23
    else:
        log.warning('Invalid month')
        sys.exit(1)

    t_ro = 14.0/(binning**2)  # readout time (s)
    test_duration = 0  # durata del test (s) ?????

    # prendo flat di prova
    filename1 = testimage(
        f"Test Image Flat {filter_name[filt]}", duration=test_duration, frametype=3, filt=filt)  # ???
    # apro immagine per ricavarmi conteggi medi
    test_flat = fits.get_data(filename1)
    average_counts = test_flat.data.mean()
    # calcolo test rate (counts/(s*pixel))
    rate = average_counts/(test_duration)

    t1 = target_counts_pixel/rate  # calcolo primo tempo / prima esposizione
    filename = testimage(f"Flat {filter_name[filt]}", duration=t1,
                         frametype=3, filt=filt, binning=binning)  # primo flat

    a = 10**(k/tau)
    S = (a**(t1)-1)/np.log(a)
    # acquisisco numero di flat richiesti
    for i in range(nit):
        t2 = np.log(a**(t1+t_ro)+S*np.log(a))/np.log(a)
        # esposizione affinché counts per pixel costante (s)
        exp = t2-(t1+t_ro)
        if exp < min_exp or exp > max_exp:
            break
        else:
            t2 = t1  # processo iterativo
            filename = testimage(
                f"Flat {filter_name[filt]}", duration=exp, frametype=3, filt=filt, binning=binning)  # flat successivi
