import os

# Set environment variable to avoid file locking issues with h5netcdf or netCDF4
os.environ["HDF5_USE_FILE_LOCKING"] = "FALSE"

from pathlib import Path
import xarray as xr
from dash.exceptions import PreventUpdate

# Local imports
from qimchi.state import _state
from qimchi.logger import logger


def read_data() -> xr.Dataset:
    """
    Utility function to read data into a xarray.Dataset

    Returns:
        xr.Dataset: Loaded xarray dataset

    """
    path = Path(_state.measurement_path)
    logger.debug(f"read_data | Reading: {path}")

    try:
        # TODONOW: h5netcdf
        # ds = xr.load_dataset(path, engine="netcdf4", lock=None)
        ds = xr.load_dataset(path, engine="zarr")
        logger.debug(f"read_data | Reading done: {path}")
        return ds
    except KeyError:
        logger.warning(f"read_data | KeyError reading: {path} | Retrying...")
        ds = xr.load_dataset(path, engine="zarr")
        logger.debug(f"read_data | Reading done: {path}")
        return ds
    except Exception as err:
        logger.error(f"read_data | Error reading: {path} | err: {err}", exc_info=True)
        raise PreventUpdate
