"""Skip duplicate jsonschema validations using shape_hash.

Monkey-patches dbtClassMixin.validate to skip jsonschema when a dict
with the same structural shape has already been validated for that class.

jsonschema validates structure (required keys, value types) not string
content, so dicts with the same "shape" always produce the same result.
This collapses ~56K validate calls to ~50 unique shapes.
"""

from __future__ import annotations

from hash_utils import shape_hash


def install_validation_cache() -> None:
    """Monkey-patch dbtClassMixin.validate to skip duplicate validations."""
    try:
        from dbt_common.dataclass_schema import dbtClassMixin
    except ImportError:
        try:
            from hologram import JsonSchemaMixin as dbtClassMixin  # type: ignore[no-redef]  # dbt 1.7
        except ImportError:
            return

    _orig_validate = dbtClassMixin.validate.__func__
    _seen: set[tuple[type, int]] = set()

    def _cached_validate(cls: type, data: object) -> None:
        if isinstance(data, dict):
            key = (cls, shape_hash(data))
            if key in _seen:
                return
            _orig_validate(cls, data)
            _seen.add(key)
        else:
            _orig_validate(cls, data)

    dbtClassMixin.validate = classmethod(_cached_validate)  # type: ignore[assignment]
