"""Core response normalization."""

import json


def _normalize_core_response(raw: object) -> dict:
    """Normalize agent output to a stable chat payload shape."""
    fallback = "I couldn't generate a response. Please try again."

    if isinstance(raw, dict):
        msg = str(raw.get("message", "")).strip()
        ui_action = raw.get("ui_action")
        out = {"message": msg or fallback}
        if isinstance(ui_action, dict) and ui_action.get("type"):
            out["ui_action"] = ui_action
        if "requires_confirmation" in raw:
            out["requires_confirmation"] = bool(raw.get("requires_confirmation"))
        return out

    text = str(raw or "").strip()
    if not text:
        return {"message": fallback}

    # If model already returned JSON payload, pass through allowed fields.
    try:
        parsed = json.loads(text)
        if isinstance(parsed, dict):
            return _normalize_core_response(parsed)
    except Exception:
        pass

    return {"message": text or fallback}
