"""Monkey-patch the Claude Agent SDK to handle unknown message types gracefully.

The SDK's parse_message() raises MessageParseError on unknown types like
rate_limit_event. This kills the async generator chain in query() ->
process_query(), preventing ResultMessage from arriving. We patch it to
return a SystemMessage for any unknown type instead of raising.

Must patch BOTH the message_parser module AND the client module — the
latter imports the name at module load time via
`from .message_parser import parse_message`, creating a separate binding.
"""

from __future__ import annotations

_patched = False


def patch_sdk() -> None:
    """Apply the parse_message monkey-patch. Idempotent."""
    global _patched
    if _patched:
        return

    try:
        from claude_agent_sdk import SystemMessage
        from claude_agent_sdk._internal import client as _client
        from claude_agent_sdk._internal import message_parser as _mp
    except ImportError:
        # SDK not installed — nothing to patch.
        return

    _orig_parse = _mp.parse_message

    def _patched_parse(data):  # type: ignore[override]
        if isinstance(data, dict):
            msg_type = data.get("type", "")
            # Catch rate_limit_event and any other unknown type the SDK
            # doesn't handle, rather than letting it raise MessageParseError.
            try:
                return _orig_parse(data)
            except Exception:
                return SystemMessage(subtype=msg_type or "unknown", data=data)
        return _orig_parse(data)

    _mp.parse_message = _patched_parse
    _client.parse_message = _patched_parse
    _patched = True
