"""Smoke tests for the feel-py bindings (mirrors the feel-wasm/feel-pg behaviour).

Run after `maturin develop`:  pytest crates/feel-py/tests
"""

import datetime

import pytest
from dateutil.relativedelta import relativedelta

import feel


# --- scalars, lists, contexts --------------------------------------------- #

def test_integer_stays_int():
    result = feel.evaluate("1 + 1")
    assert result == 2
    assert isinstance(result, int)  # not 2.0


def test_path_access_reads_nested_context():
    assert feel.evaluate("p.age", {"p": {"age": 42}}) == 42


def test_for_loop_returns_list():
    assert feel.evaluate("for i in [1,2,3] return i + 1") == [2, 3, 4]


def test_context_literal_returns_dict():
    assert feel.evaluate("{a: 1, b: a + 1}") == {"a": 1, "b": 2}


# --- lenient / strict null (ADR-14) --------------------------------------- #

def test_type_error_is_lenient_none():
    assert feel.evaluate("1 + true") is None


def test_strict_raises_on_error_null():
    with pytest.raises(feel.FeelError):
        feel.evaluate_strict("1 + true")


def test_strict_passes_plain_null():
    assert feel.evaluate_strict("null") is None


def test_parse_error_raises():
    with pytest.raises(feel.FeelError):
        feel.compile("1 +")


# --- temporal mapping (ADR-18) -------------------------------------------- #

def test_date_maps_to_date():
    assert feel.evaluate("date(2017, 8, 3)") == datetime.date(2017, 8, 3)


def test_days_time_duration_maps_to_timedelta():
    assert feel.evaluate('duration("P3D")') == datetime.timedelta(days=3)


def test_years_months_duration_maps_to_relativedelta():
    assert feel.evaluate('duration("P1Y2M")') == relativedelta(years=1, months=2)


def test_datetime_roundtrips_through_context():
    # A native datetime in the context comes back out as a datetime.
    dt = datetime.datetime(2017, 8, 10, 12, 30, 0)
    assert feel.evaluate("x", {"x": dt}) == dt


# --- regex dialect = Python `re` (ADR-16) --------------------------------- #

def test_regex_backreference_is_python_dialect():
    # Backreferences exist in Python `re` but not in the Rust regex engine, so a
    # true result proves the Python dialect is active.
    assert feel.evaluate(r'matches("abab", "(ab)\1")') is True


def test_regex_flag_argument():
    assert feel.evaluate('matches("ABC", "abc", "i")') is True


def test_regex_inline_flag():
    assert feel.evaluate('matches("ABC", "(?i)abc")') is True


def test_regex_replace_group_reference():
    assert feel.evaluate('replace("abc", "(a)(b)", "$2$1")') == "bac"


# --- object context: lazy attribute access (ADR-21) ----------------------- #

def test_dataclass_context_reads_instance_data():
    from dataclasses import dataclass

    @dataclass
    class Order:
        total: int

    assert feel.evaluate("o.total", {"o": Order(99)}) == 99


def test_nested_object_path():
    from dataclasses import dataclass

    @dataclass
    class Customer:
        name: str

    @dataclass
    class Order:
        customer: Customer

    assert feel.evaluate("o.customer.name", {"o": Order(Customer("Ada"))}) == "Ada"


def test_property_fires_when_path_names_it():
    # Lazy access is `getattr`, so naming a property in the path evaluates it —
    # exactly once, on access. This is the ORM lazy-load use case.
    fired = []

    class Row:
        @property
        def computed(self):
            fired.append(True)
            return 7

    assert feel.evaluate("r.computed", {"r": Row()}) == 7
    assert fired == [True]


def test_untouched_property_is_not_fired():
    # Attribute-level laziness: reading one member never fires a *sibling*
    # property — only the attributes the expression actually names are touched.
    fired = []

    class Row:
        def __init__(self):
            self.total = 5

        @property
        def side_effect(self):
            fired.append(True)
            return 1

    assert feel.evaluate("r.total", {"r": Row()}) == 5
    assert fired == []


def test_lazy_relation_loads_only_when_navigated():
    loads = []

    class Address:
        def __init__(self):
            self.city = "Berlin"

    class Customer:
        @property
        def address(self):  # a lazily-loaded relation (a DB hit, in real life)
            loads.append(True)
            return Address()

    class Order:
        def __init__(self):
            self.customer = Customer()

    # Navigating into the relation triggers exactly one load.
    assert feel.evaluate("o.customer.address.city", {"o": Order()}) == "Berlin"
    assert loads == [True]
    # Not naming the relation triggers no load.
    loads.clear()
    assert feel.evaluate("o.customer", {"o": Order()}) is not None
    assert loads == []


# --- output pass-through (ADR-21) ----------------------------------------- #

def test_foreign_object_result_passes_through_by_identity():
    # A host object that reaches the result comes back as the *same* object, not a
    # snapshot dict — no re-traversal.
    class Customer:
        def __init__(self):
            self.name = "Ada"

    c = Customer()
    assert feel.evaluate("o", {"o": c}) is c
    assert feel.evaluate("o.self", {"o": {"self": c}}) is c


# --- cyclic graphs need no guard in lazy mode (ADR-21) -------------------- #

def test_self_referential_dict_terminates_via_finite_path():
    d = {"a": 1}
    d["self"] = d
    # A finite expression names a finite path, so this terminates with no guard.
    assert feel.evaluate("x.self.self.self.a", {"x": d}) == 1
    # And the cyclic object passes through by identity.
    assert feel.evaluate("x.self", {"x": d}) is d


# --- descendant `e ... name` (DMN 10.3.2.7, grammar rule 68) -------------- #
#
# Descendant recursively collects every value bound to `name` in `e` and all nested
# contexts. Unlike the lazy `.`, it is an *unbounded* traversal, so a cyclic Python
# object would loop forever without the `identity()` override (which keys on the
# Python object pointer, i.e. `id()`).

def test_descendant_spec_example():
    assert feel.evaluate("{a: {b: {b: 1}}} ... b") == [{"b": 1}, 1]


def test_descendant_collects_across_list_of_dicts():
    assert feel.evaluate("[{x:1},{x:2}] ... x") == [1, 2]


def test_descendant_no_match_is_empty_list():
    assert feel.evaluate("{a:1} ... z") == []


def test_descendant_descends_into_nested_object():
    from dataclasses import dataclass

    @dataclass
    class Customer:
        name: str

    @dataclass
    class Order:
        customer: Customer

    assert feel.evaluate("o ... name", {"o": Order(Customer("Ada"))}) == ["Ada"]


def test_descendant_terminates_on_cyclic_dict():
    # A self-referential dict: `next` points back to the same object (same `id()`).
    # The visited-set (keyed on the Python pointer) breaks the back-edge after the
    # first re-entry, so this terminates and yields a finite, non-empty list.
    d = {"value": 42}
    d["next"] = d
    result = feel.evaluate("c ... value", {"c": d})
    assert result == [42, 42]


def test_descendant_terminates_on_cyclic_instance():
    # Same cycle, but via a class instance with a self-referential attribute
    # (the realistic ORM/object-graph shape). Distinct fresh `Arc`s per access are
    # bridged by the `id()`-based identity.
    class Node:
        pass

    n = Node()
    n.value = 7
    n.next = n
    assert feel.evaluate("n ... value", {"n": n}) == [7, 7]



# --- compile reuse -------------------------------------------------------- #

def test_compile_reused_across_contexts():
    prog = feel.compile("a + 1")
    assert prog.evaluate({"a": 1}) == 2
    assert prog.evaluate({"a": 41}) == 42


# --- host callables: Python functions invoked from FEEL (ADR-23) ---------- #

def test_callable_in_context_is_invoked():
    # A Python callable bound in the context is invoked by name from FEEL.
    assert feel.evaluate("f(2, 3)", {"f": lambda a, b: a + b}) == 5


def test_named_args_become_kwargs():
    # FEEL named arguments map to Python keyword arguments.
    assert feel.evaluate("f(b: 3, a: 2)", {"f": lambda a, b: a - b}) == -1


def test_mixed_positional_and_named():
    # Mixed positional + named (a tolerant superset of FEEL spec rule 39): 2 - 3.
    assert feel.evaluate("f(2, b: 3)", {"f": lambda a, b: a - b}) == -1


def test_host_default_applies_when_arg_omitted():
    # feel-core does no arity check for host callables, so the host's default fills in.
    assert feel.evaluate("f(2)", {"f": lambda a, b=10: a + b}) == 12


def test_keyword_only_parameter():
    # A keyword-only parameter is reachable via the named form.
    def f(a, *, b):
        return a - b

    assert feel.evaluate("f(2, b: 3)", {"f": f}) == -1


def test_host_function_receives_object_argument():
    # A host object passed as an argument round-trips: the function sees the
    # original object (identity), not a snapshot.
    class Order:
        def __init__(self):
            self.total = 99

    seen = {}

    def grab(o):
        seen["o"] = o
        return o.total

    order = Order()
    assert feel.evaluate("grab(o)", {"grab": grab, "o": order}) == 99
    assert seen["o"] is order


def test_host_function_via_registry():
    # The second injection path: an ambient `functions=` registry, separate from data.
    assert feel.evaluate("add(2, 3)", functions={"add": lambda a, b: a + b}) == 5
    # Combined with a data context.
    assert (
        feel.evaluate("add(x, 3)", {"x": 2}, functions={"add": lambda a, b: a + b}) == 5
    )


def test_host_exception_is_lenient_none():
    # A raised exception inside the host callable becomes an error-null (-> None).
    def boom(a):
        raise ValueError("nope")

    assert feel.evaluate("f(1)", {"f": boom}) is None


def test_returned_callable_passes_through_by_identity():
    # A host callable that reaches the result is handed back as the same object.
    f = lambda a: a
    assert feel.evaluate("f", {"f": f}) is f


def test_context_binding_shadows_builtin():
    # A function-valued context binding takes precedence over a built-in of the
    # same name (host override; ADR-23).
    assert feel.evaluate("count(1, 2)", {"count": lambda a, b: a * b}) == 2


# --- `instance of`: structural shape checks over Python objects (ADR-26) -- #
#
# FEEL is *structurally* typed (like TypeScript): `value instance of context<…>`
# asserts the value has *at least* the named fields with conforming types — it does
# NOT consult the Python class name (that would be `isinstance`, which is nominal and
# non-portable). So `instance of` is a host-agnostic "duck-typed shape" assertion.

def test_instance_of_builtin_types():
    # Over native values, against the built-in types.
    assert feel.evaluate('"foo" instance of string') is True
    assert feel.evaluate("42 instance of number") is True
    assert feel.evaluate("42 instance of string") is False
    # A null is an instance only of `Null`; a type that can't be mapped -> null.
    assert feel.evaluate("null instance of Null") is True
    assert feel.evaluate("null instance of string") is False
    assert feel.evaluate("42 instance of list") is None  # bare `list` needs a parameter


def test_instance_of_checks_dict_shape():
    # The common case: a JSON-like dict. Width subtyping — extra keys are fine.
    order = {"id": 7, "customer": "Ada"}
    assert feel.evaluate("o instance of context<customer: string>", {"o": order}) is True
    assert feel.evaluate(
        "o instance of context<id: number, customer: string>", {"o": order}
    ) is True
    assert feel.evaluate("o instance of context<customer: number>", {"o": order}) is False
    assert feel.evaluate("o instance of context<missing: string>", {"o": order}) is False


def test_instance_of_checks_object_shape():
    # A class instance is materialised from its instance ``__dict__`` for the check,
    # so a plain dataclass works exactly like the dict above.
    from dataclasses import dataclass

    @dataclass
    class Person:
        name: str
        age: int

    p = Person("Ada", 36)
    assert feel.evaluate("p instance of context<name: string>", {"p": p}) is True
    assert feel.evaluate(
        "p instance of context<name: string, age: number>", {"p": p}
    ) is True
    assert feel.evaluate("p instance of context<age: number>", {"p": p}) is True
    assert feel.evaluate("p instance of context<name: number>", {"p": p}) is False


def test_instance_of_sees_instance_data_not_properties():
    # CAVEAT: the shape check materialises the instance ``__dict__`` (real data
    # attributes). A computed ``@property`` is *not* part of that view — even though
    # the FEEL dot (``r.doubled``) *does* fire it. The two paths differ on purpose:
    # bulk materialisation for `instance of` vs. lazy attribute access for the dot.
    class Row:
        def __init__(self):
            self.total = 10

        @property
        def doubled(self):
            return self.total * 2

    r = Row()
    assert feel.evaluate("r.doubled", {"r": r}) == 20  # the dot fires the property
    assert feel.evaluate("r instance of context<total: number>", {"r": r}) is True
    # The property is invisible to the structural check:
    assert feel.evaluate("r instance of context<doubled: number>", {"r": r}) is False


def test_instance_of_slots_object_is_not_introspectable():
    # CAVEAT: a ``__slots__`` object has no ``__dict__``, so it cannot be materialised
    # into a context — the predicate is False (not an error). Lazy dot access still
    # works.
    class Point:
        __slots__ = ("x", "y")

        def __init__(self, x, y):
            self.x = x
            self.y = y

    pt = Point(1, 2)
    assert feel.evaluate("pt.x", {"pt": pt}) == 1  # the dot still works
    assert feel.evaluate("pt instance of context<x: number>", {"pt": pt}) is False


def test_instance_of_field_may_be_null():
    # A *missing* field fails the check, but a field that is present and ``None``
    # conforms to any type — in the FEEL lattice ``Null`` is a subtype of every type.
    # So this asserts "has a ``name`` slot (possibly null) that, when non-null, is a
    # string", not "has a non-null string name".
    class Person:
        def __init__(self, name):
            self.name = name

    assert feel.evaluate("p instance of context<name: string>", {"p": Person(None)}) is True
    assert feel.evaluate("p instance of context<name: string>", {"p": Person("Ada")}) is True


def test_instance_of_nested_and_list_shapes():
    # Generics compose: ``list<…>`` over elements and nested ``context<…>``.
    people = [{"name": "Ada"}, {"name": "Grace"}]
    assert feel.evaluate(
        "ps instance of list<context<name: string>>", {"ps": people}
    ) is True
    # One element of the wrong shape fails the whole list.
    assert feel.evaluate(
        "ps instance of list<context<name: number>>", {"ps": people}
    ) is False
    nested = {"owner": {"name": "Ada"}}
    assert feel.evaluate(
        "c instance of context<owner: context<name: string>>", {"c": nested}
    ) is True
    assert feel.evaluate(
        "c instance of context<owner: context<name: number>>", {"c": nested}
    ) is False
