"""Best-effort execution helpers for agent_loop_run optional paths."""
from __future__ import annotations

import json
import logging
from collections.abc import Callable
from typing import Any, TypeVar

T = TypeVar("T")
_DEFAULT_LOG = logging.getLogger(__name__)


def best_effort(
    fn: Callable[[], None],
    *,
    log: str,
    logger: logging.Logger | None = None,
) -> None:
    """Run *fn*; log at debug with traceback and swallow any exception."""
    try:
        fn()
    except Exception:
        (logger or _DEFAULT_LOG).debug(log, exc_info=True)


def best_effort_reset(
    reset_fn: Callable[[Any], None],
    token: Any,
    *,
    log: str,
    logger: logging.Logger | None = None,
) -> None:
    """Call ``reset_fn(token)`` inside :func:`best_effort`."""
    best_effort(lambda: reset_fn(token), log=log, logger=logger)


def best_effort_value(
    fn: Callable[[], T],
    *,
    log: str,
    default: T,
    logger: logging.Logger | None = None,
) -> T:
    """Return ``fn()`` or *default* after logging on failure."""
    try:
        return fn()
    except Exception:
        (logger or _DEFAULT_LOG).debug(log, exc_info=True)
        return default


def int_from_mapping(mapping: dict[str, Any], key: str, default: int) -> int:
    """Read an int from a config mapping; return *default* on type/value errors."""
    try:
        return int(mapping.get(key, default))
    except (TypeError, ValueError):
        return default


def json_dict_from_str(
    raw: str,
    *,
    log: str,
    logger: logging.Logger | None = None,
) -> dict[str, Any]:
    """Parse JSON object text; return ``{}`` and log on decode failure."""
    try:
        if not isinstance(raw, str) or not raw.strip():
            return {}
        val = json.loads(raw)
        return val if isinstance(val, dict) else {}
    except json.JSONDecodeError:
        (logger or _DEFAULT_LOG).debug(log, exc_info=True)
        return {}
