from __future__ import annotations

import json
from typing import Any


def build_risk_rule_version_markdown(payload: dict[str, Any]) -> str:
    metadata = payload.get("metadata") if isinstance(payload.get("metadata"), dict) else {}
    fields = (
        payload.get("inputs", {}).get("fields") if isinstance(payload.get("inputs"), dict) else []
    )
    field_labels = [
        str(item.get("label") or item.get("key") or "").strip()
        for item in fields
        if isinstance(item, dict) and str(item.get("label") or item.get("key") or "").strip()
    ]
    return "\n".join(
        [
            f"# {payload.get('name')}",
            "",
            "## 业务说明",
            "",
            str(payload.get("description") or ""),
            "",
            "## 自然语言原文",
            "",
            str(metadata.get("natural_language") or ""),
            "",
            "## 使用字段",
            "",
            "、".join(field_labels) or "未识别字段",
            "",
            "## 运行时 JSON",
            "",
            "```json",
            json.dumps(payload, ensure_ascii=False, indent=2),
            "```",
        ]
    )
