"""Core functionality for loading layers and preparing them."""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/00_core.ipynb.

# %% auto 0
__all__ = ['get_demo_path', 'load_config', 'run_steps', 'str_to_resampling', 'pathstem', 'pathname']

# %% ../nbs/00_core.ipynb 4
import rasterio
from rasterio.warp import calculate_default_transform, reproject, Resampling
import numpy as np
import pandas as pd
import geopandas as gpd

# %% ../nbs/00_core.ipynb 7
from importlib.resources import files

def get_demo_path(filename):
    return files("muir.demo").joinpath(filename)

# %% ../nbs/00_core.ipynb 10
import yaml
import os

def load_config(config_path, dlt=[]):
    def _update_paths(d, base_path):
        if isinstance(d, dict):
            for k, v in d.items():
                if isinstance(v, (dict, list)):
                    _update_paths(v, base_path)
                elif isinstance(k, str) and "path" in k and k != "base_data_path" and isinstance(v, str):
                    if not os.path.isabs(v):
                        d[k] = os.path.join(base_path, v)
        elif isinstance(d, list):
            for item in d:
                _update_paths(item, base_path)
    with open(config_path) as f:
        config = yaml.safe_load(f)

    # update raster and vector paths to absolute paths
    if "base_data_path" in config and config["base_data_path"] is not None:
        # demo only
        if config["base_data_path"] == "[DEMO]":
            config["base_data_path"] = get_demo_path("")
            _update_paths(config, config["base_data_path"])

    # remove keys
    for key in dlt:
        if key in config:
            del config[key]
                    
    return config

# %% ../nbs/00_core.ipynb 15
import tempfile
import os

def run_steps(start_path, end_path, steps):
    """
    Chain a sequence of processing steps, handling temp files for intermediates.
    Each step is a tuple: (func, kwargs_dict)
    - func: function(input_path, output_path, **kwargs)
    - kwargs_dict: dict of additional keyword arguments for the function
    """
    temp_paths = []
    try:
        in_path = start_path
        for i, (func, kwargs) in enumerate(steps):
            # Last step writes to end_path, others to temp files
            if i == len(steps) - 1:
                out_path = end_path
            else:
                tmp = tempfile.NamedTemporaryFile(suffix=".tif", delete=False)
                out_path = tmp.name
                tmp.close()
                temp_paths.append(out_path)
            status = func(input_path=in_path, output_path=out_path, **kwargs)
            if status != SKIP_SYMBOL: # function carried out
                in_path = out_path
    finally:
        for p in temp_paths:
            if os.path.exists(p):
                os.remove(p)


# %% ../nbs/00_core.ipynb 16
def str_to_resampling(resampling_str):
    """
    Convert a string to a rasterio.enums.Resampling enum value.
    Example: "nearest" -> Resampling.nearest
    """
    try:
        return Resampling[resampling_str.lower()]
    except KeyError:
        raise ValueError(f"Unknown resampling method: {resampling_str}")

# %% ../nbs/00_core.ipynb 17
from pathlib import Path
def pathstem(input_path):
    return Path(input_path).stem
def pathname(input_path):
    return Path(input_path).name
