"""Utility helper functions for Tru-Guard."""

import inspect
from typing import Any, Callable, get_type_hints


def extract_init_parameters(cls: type) -> dict[str, Any]:
    """Extract parameter information from a class's __init__ method.

    Args:
        cls: The class to extract parameters from

    Returns:
        Dictionary mapping parameter names to their type annotations
    """
    params: dict[str, Any] = {}

    try:
        hints = get_type_hints(cls.__init__)
    except Exception:
        hints = {}

    sig = inspect.signature(cls.__init__)
    for name, param in sig.parameters.items():
        if name in ("self", "kwargs", "args"):
            continue

        param_info: dict[str, Any] = {}

        # Get type annotation
        if name in hints:
            param_info["type"] = hints[name]
        elif param.annotation != inspect.Parameter.empty:
            param_info["type"] = param.annotation

        # Get default value
        if param.default != inspect.Parameter.empty:
            param_info["default"] = param.default

        # Check if required
        param_info["required"] = param.default == inspect.Parameter.empty

        params[name] = param_info

    return params


def validate_scan_type_compatibility(
    scanner_scan_types: list[str],
    requested_scan_type: str,
) -> bool:
    """Check if a scanner supports the requested scan type.

    Args:
        scanner_scan_types: List of scan types the scanner supports
        requested_scan_type: The scan type being requested

    Returns:
        True if the scanner supports the requested scan type
    """
    return requested_scan_type in scanner_scan_types


def truncate_string(s: str, max_length: int = 100, suffix: str = "...") -> str:
    """Truncate a string to a maximum length.

    Args:
        s: The string to truncate
        max_length: Maximum length including suffix
        suffix: Suffix to append if truncated

    Returns:
        Truncated string
    """
    if len(s) <= max_length:
        return s
    return s[: max_length - len(suffix)] + suffix


def merge_metadata(*dicts: dict[str, Any]) -> dict[str, Any]:
    """Merge multiple metadata dictionaries.

    Later dictionaries take precedence for conflicting keys.

    Args:
        *dicts: Dictionaries to merge

    Returns:
        Merged dictionary
    """
    result: dict[str, Any] = {}
    for d in dicts:
        result.update(d)
    return result
