import os
import yaml
import pandas as pd
from mrio_toolbox.utils.savers._path_checker import check_path
import logging

log = logging.getLogger(__name__)

def save_to_nc(obj,path,overwrite=False,write_instructions=False,**kwargs):
    """
    Save an MRIO or Path instance in a .nc file

    Parameters
    ----------
    path : str
        Path to the .nc file to save the MRIO instance into.
    
    **kwargs : dict
        Additional arguments to pass to the saver.
    """
    log.info(f"Saving {obj.__class__.__name__} instance to {path}")
    ds = obj.to_xarray()
    for index in ds.indexes:
        if isinstance(ds.indexes[index],pd.MultiIndex):
            import cf_xarray as cfxr
            #Compress MultiIndex data as it is not supported by xarray
            ds = cfxr.encode_multi_index_as_compress(ds,index)

    #Remove dict attrs (not supported for serialization)
    attrs = list(ds.attrs.keys())
    for attr in attrs:
        if isinstance(ds.attrs[attr],dict):
            log.warning(f"Attribute {attr} is a dict. It will not be saved.")
            ds.attrs.pop(attr)
    
    for var in ds.data_vars:
        attrs = list(ds[var].attrs.keys())
        for attr in attrs:
            if isinstance(ds[var].attrs[attr],dict):
                log.warning(f"Attribute {attr} of {var} is a dict. It will not be saved.")
                ds[var].attrs.pop(attr)

    if not overwrite:
        base_path = os.path.splitext(path)[0]
        path = check_path(base_path)
    ds.to_netcdf(path+".nc",**kwargs)
    if write_instructions:
        instructions = {
            "file": path+".nc"
        }
        with open(path+".yaml","w") as file:
            yaml.dump(instructions,file)