"""Display-only, observation-local PoseC3D thresholds. No model execution."""
import math

THRESHOLDS = {23: (0.00003, 0.00006, 0.00010),
              49: (0.00006, 0.00010, 0.00020),
              50: (0.00010, 0.00020, 0.00040),
              51: (0.002, 0.004, 0.008)}
NAMES = {23: 'kicking something', 49: 'punching/slapping other person',
         50: 'kicking other person', 51: 'pushing other person'}
VARIANTS = {'signals_3levels': None, 'filtered_ge2': 2, 'filtered_ge3': 3}
WIDTH, HEIGHT = 3200, 1800


def observation(record):
    result = {k: record[k] for k in ('sample', 'source_frame', 'seconds')}
    result.update(valid=False, state='NO_SCORES', count=None, passed_ids=[], classes={}, ge2=None, ge3=None)
    items = [it for it in record.get('items', []) if it.get('scores') is not None]
    if not items:
        statuses = [record.get('status')] + [it.get('status') for it in record.get('items', [])]
        if 'INSUFFICIENT_WINDOW' in statuses:
            result['state'] = 'INPUT_INSUFFICIENT'
        elif 'NO_VALID_SKELETON' in statuses:
            result['state'] = 'NO_VALID_SKELETON'
        return result
    if len(items) != 1:
        raise ValueError('PoseC3D must have one scene-level score vector')
    scores = items[0]['scores']
    if len(scores) != 60 or not all(isinstance(v, (float, int)) and not isinstance(v, bool)
                                  and math.isfinite(v) and 0 <= v <= 1 for v in scores):
        raise ValueError('Invalid raw score vector')
    for key, thresholds in THRESHOLDS.items():
        low, basic, high = (scores[key] >= t for t in thresholds)
        result['classes'][str(key)] = dict(score=scores[key], low=low, basic=basic, high=high)
        if basic:
            result['passed_ids'].append(key)
    count = len(result['passed_ids'])
    result.update(valid=True, state='VALID', count=count, ge2=count >= 2, ge3=count >= 3)
    return result


def display_state(decision, variant):
    if not decision['valid']:
        return decision['state']
    minimum = VARIANTS[variant]
    return 'SIGNALS' if minimum is None else 'PASS' if decision['count'] >= minimum else 'NO_MATCH'


def score_text(value):
    if 0 < value < 1e-9:
        return f'{value:.3e}'
    return f'{value:.9f}'
