from __future__ import annotations

from copy import deepcopy
from typing import Any

from app.services.risk_rule_generation_interpreter import build_dsl_from_semantic_plan


DSL_PAYLOAD_KEYS = ("dsl", "json_dsl", "rule_dsl", "rule")


def unwrap_semantic_plan_payload(payload: dict[str, Any]) -> dict[str, Any]:
    """兼容旧版扁平 JSON 与新版 semantic_plan + DSL 包装结构。"""

    if not isinstance(payload, dict):
        return {}
    semantic_plan = payload.get("semantic_plan")
    semantic_plan = semantic_plan if isinstance(semantic_plan, dict) else {}
    dsl = next((payload.get(key) for key in DSL_PAYLOAD_KEYS if isinstance(payload.get(key), dict)), None)
    if not isinstance(dsl, dict):
        result = build_dsl_from_semantic_plan(semantic_plan) or deepcopy(payload)
        if semantic_plan:
            result["model_semantic_plan"] = semantic_plan
        return result

    result = deepcopy(dsl)
    if semantic_plan:
        result["model_semantic_plan"] = semantic_plan
    for key in ("name", "description", "flow", "risk_scoring_evidence", "unsupported_fields"):
        if key not in result and key in payload:
            result[key] = deepcopy(payload[key])
    return result
