"""
General utility functions.
"""

import time
import uuid
from typing import Any


def get_timestamp() -> float:
    """Get current Unix timestamp."""
    return time.time()


def generate_request_id() -> str:
    """Generate a unique request ID."""
    return str(uuid.uuid4())[:8]


def bytes_to_hex(data: bytes) -> str:
    """Convert bytes to hex string."""
    return data.hex()


def hex_to_bytes(hex_str: str) -> bytes:
    """Convert hex string to bytes."""
    return bytes.fromhex(hex_str)


def bytes_to_base64(data: bytes) -> str:
    """Convert bytes to base64 string."""
    import base64

    return base64.b64encode(data).decode("ascii")


def base64_to_bytes(b64_str: str) -> bytes:
    """Convert base64 string to bytes."""
    import base64

    return base64.b64decode(b64_str)


def parse_data_input(data_str: str) -> bytes:
    """
    Parse data input string.

    Formats:
    - hex:01020304 -> bytes from hex
    - text:hello -> bytes from text
    - base64:AQIDBA== -> bytes from base64
    - 01020304 -> bytes from hex (default)
    """
    if data_str.startswith("hex:"):
        return hex_to_bytes(data_str[4:])
    elif data_str.startswith("text:"):
        return data_str[5:].encode("utf-8")
    elif data_str.startswith("base64:"):
        return base64_to_bytes(data_str[7:])
    else:
        return hex_to_bytes(data_str)


def format_data_output(data: bytes, format_type: str = "hex") -> str:
    """
    Format data for output.

    Args:
        data: Bytes to format
        format_type: Output format (hex, base64, text)

    Returns:
        Formatted string
    """
    if format_type == "hex":
        return bytes_to_hex(data)
    elif format_type == "base64":
        return bytes_to_base64(data)
    elif format_type == "text":
        try:
            return data.decode("utf-8")
        except UnicodeDecodeError:
            return bytes_to_hex(data)
    else:
        return bytes_to_hex(data)
