"""
Utility functions for fabias.
"""

import re
from typing import Any, Optional


def coalesce(*args, default=None) -> Any:
    """
    Return first non-None value from arguments or dict keys.

    Supports two usage patterns:

    1. Value coalescing - returns first non-None value:
        coalesce(val1, val2, val3)
        coalesce(None, '', 'default')  # Returns ''
        coalesce(None, None, 42)       # Returns 42

    2. Dict key lookup - tries keys in order:
        coalesce(data, 'id', 'runId', 'jobId', default='unknown')
        coalesce(headers, 'Location', 'location', default=None)

    Args:
        *args: Either values to coalesce, or (dict, key1, key2, ...)
        default: Final fallback value if all are None (keyword-only)

    Returns:
        First non-None value found, or default

    Examples:
        >>> coalesce(None, 'found', 'ignored')
        'found'
        >>> coalesce({'id': 123}, 'id', 'runId')
        123
        >>> coalesce({'name': 'test'}, 'id', 'runId', default='N/A')
        'N/A'
    """
    if not args:
        return default

    # Pattern detection: dict mode if first arg is dict and second (if exists) is string
    if isinstance(args[0], dict) and (len(args) == 1 or isinstance(args[1], str)):
        # Dict key lookup mode: coalesce(dict, 'key1', 'key2', ...)
        data = args[0]
        keys = args[1:]
        return next((data[k] for k in keys if k in data), default)

    # Value coalescing mode: coalesce(val1, val2, val3, ...)
    return next((v for v in args if v is not None), default)


class GUID:
    """
    Utility class for GUID validation and generation.
    """

    # GUID pattern: 8-4-4-4-12 hex characters
    PATTERN = re.compile(
        r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
    )

    @classmethod
    def valid(cls, value: Optional[str]) -> bool:
        """
        Check if a string is a valid GUID format.

        Args:
            value: String to validate

        Returns:
            bool: True if valid GUID format
        """
        if not value or not isinstance(value, str):
            return False
        return bool(cls.PATTERN.match(value))

    @classmethod
    def hex(cls) -> str:
        """
        Generate a new random GUID without hyphens.

        Returns:
            str: 32-character hex string
        """
        import uuid

        return uuid.uuid4().hex

    @classmethod
    def new(cls) -> str:
        """
        Generate a new random GUID.

        Returns:
            str: Standard GUID format (8-4-4-4-12)
        """
        import uuid

        return str(uuid.uuid4())


async def delay(milliseconds: int) -> None:
    """
    Async delay for specified milliseconds.

    Args:
        milliseconds: Time to wait
    """
    import asyncio

    await asyncio.sleep(milliseconds / 1000)


def sync_delay(seconds: float) -> None:
    """
    Synchronous delay for specified seconds.

    Args:
        seconds: Time to wait
    """
    from time import sleep

    sleep(seconds)
