"""Utility module for DROP"""

import os
import shutil
from glob import glob
# from aqua.core.util import dump_yaml, load_yaml
# from aqua.core.util import ConfigPath
# from aqua.core.logger import log_configure


# def opa_catalog_entry(datadir, model, exp, source, catalog=None,
#                       fixer_name=False, frequency='monthly',
#                       loglevel='WARNING'):
#     """
#     Create an entry in the AQUA catalog based on the presence of output from OPA in datadir
#     to be used by DROP in both source and regrid yaml

#     Args:
#         datadir (str): path to the directory containing the data
#         catalog (str): name of the catalog, None for getting it automatically
#         model (str): name of the model
#         exp (str): name of the experiment
#         source (str): name of the origin source
#         fixer_name (str): fix to be used when reading the opa. Default is False
#         frequency (str, opt): frequency of the data, default is 'monthly'
#         loglevel (str, opt): logging level, default is 'WARNING'

#     Returns:
#         entry_name (str): name of the entry created in the catalog

#     Raises:
#         KeyError: if the origin source is not found in the catalog
#     """
#     logger = log_configure(log_level=loglevel, log_name='opa_catalog_entry')

#     entry_name = 'opa'
#     entry_name += '_%s' % source
#     logger.info('Creating catalog entry %s %s %s', model, exp, entry_name)

#     # load the catalog experiment file
#     Configurer = ConfigPath()
#     configdir = Configurer.configdir
#     if catalog is None:
#         catalog = Configurer.catalog

#     # find the catalog of my experiment
#     catalogfile = os.path.join(configdir, 'catalogs', catalog,
#                                'catalog', model, exp + '.yaml')

#     # load, add the block and close
#     cat_file = load_yaml(catalogfile)

#     # NOTE: commented because the correct grid is lon-lat when generated by OPA
#     #       see issue #691
#     # # read the grid info from the origin source
#     # if source in cat_file['sources']:
#     #     try:
#     #         grid = cat_file['sources'][source]['metadata']['source_grid_name']
#     #     except KeyError:
#     #         logger.error('Cannot find source grid name in catalog, assuming lon-lat')
#     #         grid = 'lon-lat'
#     # else:
#     #     raise KeyError('Cannot find source %s in catalog' % source)

#     # define the block to be uploaded into the catalog
#     description = 'OPA output from %s as origin source' % source

#     block_cat = {
#         'driver': 'netcdf',
#         'args': {
#             'urlpath': os.path.join(datadir, f'*{frequency}_mean.nc'),
#             'chunks': {},
#             'xarray_kwargs': {
#                 'decode_times': True,
#                 'combine': 'by_coords'
#             }
#         },
#         'description': description,
#         'metadata': {
#             'source_grid_name': 'lon-lat',
#             'fixer_name': fixer_name
#         }
#     }

#     # add the block to the catalog
#     cat_file['sources'][entry_name] = block_cat
#     dump_yaml(outfile=catalogfile, cfg=cat_file)

#     return entry_name


def list_drop_files_complete(path):
    """
    List DROP-generated files in the specified path based on the given parameters.

    Args:
        path (str): The base path where the DROP-generated files are located.

    Returns:
        A dictionary containing the netcdf files for a each DROP variable
    """

    yearly_dict = {}
    monthly_dict = {}
    searchpath = "*"
    yearly_dict['files'] = sorted(glob(os.path.join(path, searchpath) + '_????.nc'))
    monthly_dict['files'] = sorted(glob(os.path.join(path, searchpath) + '_??????.nc'))

    # path = os.path.join(path, model, exp, reso, freq)
    return yearly_dict, monthly_dict


# NOT USED AT THE MOMENT
# def list_drop_files_vars(path):
#     """
#     List DROP files in the specified path based on the given parameters.

#     Args:
#         path (str): The base path where the DROP files are located.


#     """

#     # path = os.path.join(path, model, exp, reso, freq)
#     searchpath = os.path.join(path, '*.nc')
#     variables = set([os.path.basename(complete).rpartition('_')[0] for complete in glob(searchpath)])
#     yearly_dict = {}
#     monthly_dict = {}
#     for var in variables:
#         yearly_dict[var] = sorted(glob(os.path.join(path, var) + '_????.nc'))
#         monthly_dict[var] = sorted(glob(os.path.join(path, var) + '_??????.nc'))

#     return yearly_dict, monthly_dict

def move_tmp_files(tmp_directory, output_directory):
    """
    Move temporary NetCDF files from the tmp directory to the output directory,
    changing their name by removing "_tmp" suffix.
    """
    if not os.path.exists(output_directory):
        os.makedirs(output_directory)

    for tmp_file in os.listdir(tmp_directory):
        if tmp_file.endswith(".nc"):
            if "_tmp" in tmp_file:
                new_file_name = tmp_file.replace("_tmp", "")
            else:
                new_file_name = tmp_file
            tmp_file_path = os.path.join(tmp_directory, tmp_file)
            new_file_path = os.path.join(output_directory, new_file_name)
            shutil.move(tmp_file_path, new_file_path)
