"""Serialization helpers for dashboard context and API responses.""" import json def _ensure_json_str(value): """Return value as JSON string; if already a string, return as-is.""" return value if isinstance(value, str) else json.dumps(value) def serialize_audit_for_response(audit: dict) -> dict: """ Return a copy of the audit dict with migrations, host_labels, cpu_current, and cpu_projected serialized as JSON strings (for template/API response). """ result = dict(audit) result["migrations"] = _ensure_json_str(audit.get("migrations")) result["host_labels"] = _ensure_json_str(audit.get("host_labels")) result["cpu_current"] = _ensure_json_str(audit.get("cpu_current")) result["cpu_projected"] = _ensure_json_str(audit.get("cpu_projected")) return result def serialize_current_cluster_for_template(current_cluster: dict) -> dict: """ Return current_cluster with host_labels and cpu_current as JSON strings for template embedding (e.g. in index.html). """ return { "host_labels": _ensure_json_str(current_cluster.get("host_labels")), "cpu_current": _ensure_json_str(current_cluster.get("cpu_current")), }