from __future__ import annotations

import base64
import hashlib
import time
import uuid as uuidlib
from datetime import datetime, timezone
from typing import Any


def echo(value: Any, *, runtime: Any) -> Any:
    return value


def sleep(seconds: int | float, *, runtime: Any) -> dict[str, Any]:
    if seconds < 0:
        raise ValueError("sleep duration must be non-negative")

    duration = min(float(seconds), float(runtime.timeout))
    time.sleep(duration)
    return {"seconds": duration, "slept": True}


def now(*, runtime: Any) -> str:
    return datetime.now(timezone.utc).isoformat()


def uuid(*, runtime: Any) -> str:
    return str(uuidlib.uuid4())


def hash_value(value: Any, algorithm: str = "sha256", *, runtime: Any) -> str:
    try:
        digest = hashlib.new(algorithm)
    except ValueError as error:
        raise ValueError(f"unsupported hash algorithm: {algorithm}") from error

    digest.update(str(value).encode("utf-8"))
    return digest.hexdigest()


def base64_encode(value: Any, *, runtime: Any) -> str:
    return base64.b64encode(str(value).encode("utf-8")).decode("ascii")


def base64_decode(value: str, *, runtime: Any) -> str:
    return base64.b64decode(value.encode("ascii")).decode("utf-8")
