# (c) cavaliba.com - data - datapoint.py

"""
Datapoint registry: named, schema-scoped values computed in code, used as
dataview columns ("datapoint: NAME" in a _dataview's YAML) when the value is
not a stored field (IPAM size/occupancy, reverse lookups, ...).

A provider is called once per list page with every instance of that page and
returns {instance.id: value}; a value is a scalar, a dict (a column picks one
entry with "key:") or a list of links [{"id": .., "label": ..}].

Method inventory: datapoint, get_datapoint, compute_datapoint.
"""

from app_home.log import WARNING, log2

# name -> {"fn": callable, "schemas": set, "widget": str, "sort_type": str | dict}
DATAPOINTS = {}

_LOADED = False


def datapoint(name, schemas, widget="text", sort_type="text"):
    """Decorator registering fn(instances, aaa, ctx) -> {instance.id: value} as
    datapoint `name`, valid on `schemas` only; `widget` is the column's default
    widget; `sort_type` (text/number/ip/key, or {key: type, "*": default}) is
    the smart-table sort type. ctx is a per-page dict shared by providers, for
    memoizing work two providers have in common."""

    def wrap(fn):
        DATAPOINTS[name] = {"fn": fn, "schemas": set(schemas), "widget": widget,
                            "sort_type": sort_type}  # fmt: skip
        return fn

    return wrap


def _load():
    """Import provider modules once, so their @datapoint decorators register."""

    global _LOADED
    if _LOADED:
        return
    _LOADED = True
    import app_data.datapoint_ipam  # noqa: F401


def get_datapoint(name):
    """Return the registry entry for datapoint `name`, or None."""

    _load()
    return DATAPOINTS.get(name)


def compute_datapoint(name, instances, aaa=None, ctx=None):
    """Run datapoint `name` over `instances`; {} on unknown name or provider
    error (logged), so one broken provider never breaks the list page."""

    entry = get_datapoint(name)
    if not entry or not instances:
        return {}
    try:
        return entry["fn"](instances, aaa, ctx if ctx is not None else {}) or {}
    except Exception as e:
        log2.fail("dataview.datapoint", reason="provider_error", level=WARNING, message=str(e),
                  target=("datapoint", name))  # fmt: skip
        return {}
