from __future__ import annotations

import json
import time
from typing import Any


class MockAzureCredential:

    _TOKEN = "mock-azure-bearer-token"

    class _Token:
        def __init__(self, token: str) -> None:
            self.token      = token
            self.expires_on = int(time.time()) + 3600

    def get_token(self, *scopes: str, **kwargs: Any) -> "_Token":
        return self._Token(self._TOKEN)

    def get_token_info(self, *scopes: str, **kwargs: Any) -> "_Token":
        return self._Token(self._TOKEN)

    def close(self) -> None:
        pass


def _get_body(request: Any) -> bytes:
    for attr in ("body", "content", "data"):
        raw = getattr(request, attr, None)
        if raw is None or raw == b"":
            continue
        if isinstance(raw, bytes):
            return raw
        if isinstance(raw, str):
            return raw.encode("utf-8")
        if hasattr(raw, "__iter__") or hasattr(raw, "__next__"):
            try:
                chunks = []
                for chunk in raw:
                    chunks.append(chunk if isinstance(chunk, bytes) else chunk.encode("utf-8"))
                return b"".join(chunks)
            except Exception:
                pass
    return b""


def _enc(body: Any) -> bytes:
    if body is None:
        return b""
    if isinstance(body, bytes):
        return body
    if isinstance(body, (dict, list)):
        return json.dumps(body, default=str).encode()
    return str(body).encode()


def _safe_json(raw: bytes) -> dict:
    try:
        return json.loads(raw) if raw else {}
    except Exception:
        return {}
