#  This code is a part of the Democratising Archival X-ray Astronomy (DAXA) module.
#  Last modified by David J Turner (turne540@msu.edu) 22/04/2024, 13:35. Copyright (c) The Contributors
import os

from daxa.archive import Archive


def create_dirs(obs_archive: Archive, miss_name: str):
    """
    This general function will set up the 'archive name'/processed_data/'ObsID' and 'archive name'/failed_data/'ObsID'
    directory structures in which the processed data for a mission (whether generated by DAXA implementations of
    missions processing, or pre-processed data downloaded from the mission data archive) are stored.

    :param Archive obs_archive: The Archive for which 'processed' and 'failed' data directories are to be created.
    :param str miss_name: The specific mission for which the 'processed' and 'failed' data directories are to
        be created. The mission name must refer to one of the missions associated with the Archive.
    """

    # We retrieve the actual mission object corresponding to the name we've been given
    miss = obs_archive[miss_name]

    # We make sure that the archive directory has folders to store each ObsID of the specified mission - the
    #  'processed_data' directories have all the ObsID directories initially, but any failed ObsIDs will be
    #  transferred over to the 'failed_data' directory which we create further down
    for obs_id in miss.filtered_obs_ids:
        stor_dir = obs_archive.construct_processed_data_path(miss, obs_id)
        if not os.path.exists(stor_dir):
            os.makedirs(stor_dir)

        # We also make a directory within the storage directory, specifically for logs
        if not os.path.exists(stor_dir + 'logs'):
            os.makedirs(stor_dir + 'logs')
        # Same deal but for different types of files that could be produced
        if not os.path.exists(stor_dir + 'images'):
            os.makedirs(stor_dir + 'images')
        if not os.path.exists(stor_dir + 'background'):
            os.makedirs(stor_dir + 'background')
        if not os.path.exists(stor_dir + 'events'):
            os.makedirs(stor_dir + 'events')
        if not os.path.exists(stor_dir + 'cleaning'):
            os.makedirs(stor_dir + 'cleaning')

    # We also ensure that an overall directory for failed processing observations exists - this will give
    #  observation directories which have no useful data in (i.e. they do not have a successful final
    #  processing step) somewhere to be moved to (see daxa.process._cleanup._last_process). Any pre-processed data
    #  downloaded from the online archives that somehow appears to have problems will also be moved over to the
    #  'failed_data' directory.
    fail_proc_dir = obs_archive.construct_failed_data_path(miss, None).format(oi='')[:-1]
    if not os.path.exists(fail_proc_dir):
        os.makedirs(fail_proc_dir)
