from __future__ import annotations

import re
from pathlib import Path
from typing import Iterable

import numpy as np

from .io import RasterData


def _slugify(value: str) -> str:
    cleaned = re.sub(r"[^a-z0-9]+", "_", value.strip().lower())
    return cleaned.strip("_") or "layer"


def export_all_bands(raster: RasterData, outdir: Path, base: str) -> Path:
    outdir.mkdir(parents=True, exist_ok=True)
    path = outdir / f"{_slugify(base)}_all.npy"
    np.save(path, raster.array)
    return path


def export_selected_bands(
    raster: RasterData, indices: list[int], outdir: Path, base: str
) -> Path:
    outdir.mkdir(parents=True, exist_ok=True)
    selected = raster.array[indices]
    path = outdir / f"{_slugify(base)}_selected.npy"
    np.save(path, selected)
    return path


def export_individual_bands(
    raster: RasterData, indices: list[int], outdir: Path, base: str
) -> list[Path]:
    outdir.mkdir(parents=True, exist_ok=True)
    paths: list[Path] = []
    for idx in indices:
        band_name = raster.band_names[idx] if idx < len(raster.band_names) else f"band_{idx+1}"
        path = outdir / f"{_slugify(base)}_{_slugify(band_name)}.npy"
        np.save(path, raster.array[idx])
        paths.append(path)
    return paths


def export_indices(index_layers: Iterable[tuple[str, np.ndarray]], outdir: Path, base: str) -> list[Path]:
    outdir.mkdir(parents=True, exist_ok=True)
    paths: list[Path] = []
    for name, array in index_layers:
        path = outdir / f"{_slugify(base)}_index_{_slugify(name)}.npy"
        np.save(path, array)
        paths.append(path)
    return paths
