"""Pupil Labs Neon — real-time gaze over the Pupil Labs Realtime API.

Neon streams gaze at 200 Hz over the network. The `pupil-labs-realtime-api`
discovers the device and yields matched gaze samples. (Pupil Core uses the LSL
Relay plugin instead — that route needs no driver, it's a tier=lsl device.)
"""

from __future__ import annotations

from ._base import DriverSource


class PupilNeonSource(DriverSource):
    def read(self):
        from pupil_labs.realtime_api.simple import discover_one_device  # lazy
        from pylsl import local_clock
        import time

        device = discover_one_device(max_search_duration_seconds=10)
        if device is None:
            raise RuntimeError("no Pupil Neon device discovered on the network")
        offset = local_clock() - time.time()
        try:
            while not self.stopping:
                g = device.receive_gaze_datum()       # blocks until next sample
                ts = getattr(g, "timestamp_unix_seconds", time.time()) + offset
                pupil = float(getattr(g, "pupil_diameter_left", 0.0) or 0.0)
                yield [float(g.x), float(g.y), pupil], ts
        finally:
            device.close()
