import time
import uuid
import hashlib
import asyncio
import polars as pl
from decimal import Decimal
from typing import Callable
from .logger import log_info


def create_uuid_from_string(val: str):
    """
    Konvertiert einen Text in eine reproduzierbare Guid
    :param val: Text
    :return: Guid als Text
    """

    hex_string = hashlib.md5(val.encode("UTF-8")).hexdigest()
    return str(uuid.UUID(hex=hex_string))


def convert_value(value: any, data_type: pl.DataType):
    match data_type:
        case pl.Decimal:
            return value if isinstance(value, Decimal) else Decimal(value)
        case pl.Float32 | pl.Float64:
            return value if isinstance(value, float) else float(value)
        case pl.Int8 | pl.Int16 | pl.Int32 | pl.Int64 | pl.UInt8 | pl.UInt16 | pl.UInt32 | pl.UInt64:
            return value if isinstance(value, int) else int(value)
        case _:
            return value

async def timer(text: str, func: Callable):
    start = time.time()
    result = func()

    if asyncio.iscoroutine(result):
        result = await result

    end = time.time()
    diff = round((end - start) * 1000, 0)

    log_info(f"{text}: {diff}ms")
    return result
