import uuid
from collections import deque
from threading import RLock


_ARTIFACTS_LOCK = RLock()
_ARTIFACTS = deque(maxlen=100)


def create_model_routing_artifact(artifact, meta=None):
    item = {
        "artifact_id": f"model-routing-{uuid.uuid4().hex[:12]}",
        "artifact": dict(artifact or {}),
        "meta": dict(meta or {}),
    }
    with _ARTIFACTS_LOCK:
        _ARTIFACTS.append(item)
    return dict(item)


def list_model_routing_artifacts(limit=20):
    max_items = max(1, int(limit or 1))
    with _ARTIFACTS_LOCK:
        items = list(_ARTIFACTS)[-max_items:]
    return [dict(item) for item in items]


def get_model_routing_artifact(artifact_id):
    wanted = str(artifact_id or "").strip()
    if not wanted:
        return None
    with _ARTIFACTS_LOCK:
        for item in reversed(_ARTIFACTS):
            if str(item.get("artifact_id") or "") == wanted:
                return dict(item)
    return None
