# src/sibi_flux/dask_cluster/utils.py
from __future__ import annotations

from typing import Any

import numpy as np
import pandas as pd


def _to_int_safe(x: Any, default: int = 0) -> int:
    """
    Safely convert a value to integer with fallback defaults.
    Optimized to avoid recursion and excessive try-except for common types.
    """
    if x is None:
        return default

    # 1. Fast path for common scalar types
    if isinstance(x, (int, np.integer)):
        if isinstance(x, bool):
            return 1 if x else 0
        return int(x)

    if isinstance(x, (float, np.floating)):
        try:
            return int(x)
        except (ValueError, OverflowError):
            return default

    # 2. Collections (Arrays, Series, Lists)
    if isinstance(x, (np.ndarray, pd.Series, pd.Index, list, tuple)):
        try:
            arr = np.asanyarray(x)
            if arr.size == 0:
                return default
            val = arr.ravel()[0]
            # Recursion replacement: simple re-check for the extracted element
            if isinstance(val, (int, np.integer, float, np.floating)):
                return _to_int_safe(val, default=default)
            return default
        except Exception:
            return default

    # 3. Duck-typing for .item() (scalar wrappers) or .iloc (Pandas)
    if hasattr(x, "item") and callable(x.item):
        try:
            return _to_int_safe(x.item(), default=default)
        except Exception:
            pass

    if hasattr(x, "iloc"):
        try:
            return _to_int_safe(x.iloc[0], default=default)
        except Exception:
            pass

    # 4. Final fallback
    try:
        return int(x)
    except (ValueError, TypeError):
        return default
