"""
APEX V18 — runtime monkey-patches for the project-x-py SDK.

These patches survive `pip install -r requirements.txt` and venv
recreation because they're applied at import time from our own code,
not by editing the installed package.

Each patch is idempotent (re-applying is a no-op via a sentinel
attribute on the patched class).

Patches:
  - Position.__init__ filter: silently ignore unknown keyword args.
    Reason: TopstepX added `contractDisplayName` (2026-05) to the
    /api/Position response and may add more fields. The original
    @dataclass __init__ rejects unknown kwargs, breaking
    positions_get(). The wrapper filters kwargs to declared fields
    before delegating, so future API additions are absorbed silently.
"""

from __future__ import annotations

import dataclasses
import logging

logger = logging.getLogger(__name__)

_PATCH_SENTINEL = "_apex_v18_patched"


def _patch_position_init() -> bool:
    """Wrap project_x_py.models.Position.__init__ to ignore unknown
    kwargs. Returns True if patch applied, False if already patched
    or SDK absent."""
    try:
        from project_x_py.models import Position
    except ImportError:
        logger.debug("SDK patch: project_x_py not installed; skipping")
        return False

    if getattr(Position, _PATCH_SENTINEL, False):
        return False

    _orig_init = Position.__init__
    _known_fields = {f.name for f in dataclasses.fields(Position)}

    def _patched_init(self, *args, **kwargs):
        filtered = {k: v for k, v in kwargs.items() if k in _known_fields}
        _orig_init(self, *args, **filtered)

    Position.__init__ = _patched_init
    setattr(Position, _PATCH_SENTINEL, True)
    logger.info(
        "SDK patch applied: Position.__init__ ignores unknown kwargs "
        "(known fields: %s)", sorted(_known_fields),
    )
    return True


def apply_sdk_patches() -> None:
    """Apply all APEX-side monkey-patches to project_x_py. Safe to
    call multiple times (each patch is idempotent)."""
    _patch_position_init()
