"""Synthetic landmark exercise. No camera, model, network or saved person data.

Original LCENJ teaching code, CC0-1.0. Python3.10+ standard library.
States describe wrist-above-shoulder in image coordinates, not exercise quality.
"""
from dataclasses import dataclass
from math import isfinite


@dataclass(frozen=True)
class Point:
    x: float
    y: float
    visibility: float


def usable(p):
    return (isinstance(p, Point)
            and all(isinstance(v, (int, float)) and not isinstance(v, bool)
                    and isfinite(v) and 0 <= v <= 1
                    for v in (p.x, p.y, p.visibility))
            and p.visibility >= 0.70)


def observation(shoulder, wrist):
    if not usable(shoulder) or not usable(wrist):
        return "unknown"
    return "above_threshold" if shoulder.y - wrist.y > 0.10 else "condition_not_met"


class HoldRule:
    def __init__(self):
        self.start_ms = None
        self.last_ms = None

    def update(self, timestamp_ms, shoulder, wrist):
        if (not isinstance(timestamp_ms, int) or isinstance(timestamp_ms, bool)
                or timestamp_ms < 0
                or self.last_ms is not None and timestamp_ms <= self.last_ms):
            raise ValueError("timestamps must be non-negative, strictly increasing ms")
        gap = self.last_ms is not None and timestamp_ms - self.last_ms > 150
        self.last_ms = timestamp_ms
        state = observation(shoulder, wrist)
        if gap or state != "above_threshold":
            self.start_ms = None
        if state != "above_threshold":
            return state
        if self.start_ms is None:
            self.start_ms = timestamp_ms
        return "confirmed_above_threshold" if timestamp_ms - self.start_ms >= 200 else "waiting"


def exercise():
    shoulder = Point(320 / 640, 210 / 480, 0.95)
    wrist = Point(360 / 640, 130 / 480, 0.95)
    cases = []
    def check(name, value):
        assert value, name
        cases.append(name)
    check("synthetic_above", observation(shoulder, wrist) == "above_threshold")
    check("wrist_below", observation(shoulder, Point(0.5, 0.8, .95)) == "condition_not_met")
    check("strict_margin_boundary", observation(Point(.5, .25, .95), Point(.5, .15, .95)) == "condition_not_met")
    check("missing_point", observation(shoulder, None) == "unknown")
    check("low_visibility", observation(shoulder, Point(.5, .1, .3)) == "unknown")
    check("out_of_frame", observation(shoulder, Point(1.1, .1, .95)) == "unknown")
    check("non_finite", observation(shoulder, Point(float('nan'), .1, .95)) == "unknown")
    rule = HoldRule()
    check("first_sample_waits", rule.update(1000, shoulder, wrist) == "waiting")
    check("100ms_waits", rule.update(1100, shoulder, wrist) == "waiting")
    check("200ms_confirms", rule.update(1200, shoulder, wrist) == "confirmed_above_threshold")
    check("gap_restarts", rule.update(1500, shoulder, wrist) == "waiting")
    check("unknown_resets", rule.update(1600, shoulder, None) == "unknown")
    check("valid_after_unknown_waits", rule.update(1700, shoulder, wrist) == "waiting")
    check("not_above_clears_hold", rule.update(1800, shoulder, Point(.5, .8, .95)) == "condition_not_met")
    try:
        rule.update(1800, shoulder, wrist)
    except ValueError:
        check("duplicate_time_rejected", True)
    else:
        raise AssertionError("duplicate timestamp accepted")
    for name in cases:
        print("PASS", name)
    print(f"{len(cases)} synthetic checks passed; no camera or pose model was run.")


if __name__ == "__main__":
    exercise()
