"""Various utilities to decode MARIS dataset from `NetCDF`."""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/api/decoders.ipynb.

# %% auto 0
__all__ = ['NetCDFDecoder']

# %% ../nbs/api/decoders.ipynb 3
from pathlib import Path
from netCDF4 import Dataset
import pandas as pd
import numpy as np
from fastcore.basics import patch, store_attr
import fastcore.all as fc
from typing import Dict, Callable

from marisco.configs import (
    NC_DTYPES, 
    NC_VARS, 
    CSV_VARS,
    NC_DIM,
    NC_GROUPS,
    SMP_TYPE_LUT,
    lut_path, 
    Enums,
    nc_tpl_path,
    get_time_units
)

from marisco.callbacks import (
    DecodeTimeCB
    )

# %% ../nbs/api/decoders.ipynb 6
class NetCDFDecoder:
    """Decode MARIS NetCDF files to human readable formats."""
    def __init__(self, 
                 dfs: Dict[str, pd.DataFrame], 
                 fname_in: str,  # Path to NetCDF file
                 dest_out: str, 
                 output_format:str, 
                 remap_vars: Dict[str, str],
                 verbose: bool=False
                ):
        fc.store_attr()        

# %% ../nbs/api/decoders.ipynb 7
@patch
def process_groups(self: NetCDFDecoder):
    """Process all groups in the dataset."""
    for group_name, df in self.dfs.items():
        self.process_group(group_name, df, self.remap_vars)

# %% ../nbs/api/decoders.ipynb 8
@patch
def process_group(self: NetCDFDecoder, group_name: str, df: pd.DataFrame, remap_vars: Dict[str, str]):
    """Process a single group, mapping column names using remap_vars."""
    # Map column names using remap_vars
    df.columns = [remap_vars.get(col, col) for col in df.columns]


# %% ../nbs/api/decoders.ipynb 9
@patch
def save_dataframes(self: NetCDFDecoder):
    """
    Save DataFrames to CSV files.
    
    Each group in the DataFrame dictionary will be saved as a separate CSV file
    with the naming pattern: {base_path}_{group_name}.csv
    
    Raises:
        ValueError: If no destination path is provided or if output format is not CSV
    """
    # Validate destination path
    if self.dest_out is None:
        self.dest_out  = str(Path(self.fname_in).with_suffix(''))
    
    # Validate output format
    if self.output_format != 'csv':
        raise ValueError("Only CSV format is supported")
    
    # Get base path without extension
    base_path = str(Path(self.dest_out).with_suffix(''))
    
    # Save each DataFrame to a CSV file
    for group_name, df in self.dfs.items():
        output_path = f"{base_path}_{group_name}.csv"
        df.to_csv(output_path, index=False)
        
        if self.verbose:
            print(f"Saved {group_name} to {output_path}")

# %% ../nbs/api/decoders.ipynb 10
@patch
def decode(self: NetCDFDecoder):
    "Decode NetCDF to Human readable files."
    # Function to rename the columns. 
    self.process_groups()
    self.save_dataframes()
    return self.dfs    
