"""Bounded private source-boundary observations, never a public clock correction."""
from functools import lru_cache
import ctypes
import os


def source_latest_enabled():
    value = os.environ.get('CONTEXTRA_SOURCE_LATEST_TRIAL', 'false')
    if value not in ('true', 'false'):
        raise ValueError('Invalid source latest trial option.')
    return value == 'true'


@lru_cache(maxsize=1)
def gap_meta_type():
    register = ctypes.CDLL('libnvds_meta.so').nvds_get_user_meta_type
    register.argtypes = [ctypes.c_char_p]
    register.restype = ctypes.c_int
    return register(b'CONTEXTRA.INPUT.GAP.V1')


@lru_cache(maxsize=1)
def meta_type():
    register = ctypes.CDLL('libnvds_meta.so').nvds_get_user_meta_type
    register.argtypes = [ctypes.c_char_p]
    register.restype = ctypes.c_int
    return register(b'CONTEXTRA.INPUT.TIMING.V1')


def read(frame):
    rows = [m.get_user_data_json() for m in frame.user_meta_items(meta_type())]
    if len(rows) != 1 or not isinstance(rows[0], dict):
        return None
    row = rows[0]
    fields = ('rtp', 'ssrc', 'rate', 'depay_first_ns', 'depay_last_ns',
              'source_exit_ns', 'source_wall_ns')
    if any(type(row.get(k)) is not int or row[k] < 0 for k in fields):
        return None
    if (not 0 <= row['rtp'] < 2**32 or not 0 <= row['ssrc'] < 2**32
            or row['rate'] <= 0
            or not 0 < row['depay_first_ns'] <= row['depay_last_ns'] <= row['source_exit_ns']):
        return None
    optional = ('encoded_in_ns', 'encoded_out_ns', 'raw_in_ns', 'raw_out_ns',
                'encoded_level', 'raw_level', 'encoded_queued_ns', 'raw_queued_ns', 'latest_applied')
    if any(type(row[k]) is not int or row[k] < 0 for k in optional if k in row):
        return None
    return {k: row[k] for k in (*fields, *optional) if k in row}
