import unittest
from unittest.mock import patch
from app.pipeline_diagnostics import PipelineDiagnostics, diagnostics, timed_copy


class ScaleDiagnosticsTest(unittest.TestCase):
    def test_bounded_histogram_reset_and_expiry(self):
        d=PipelineDiagnostics()
        p=d.for_provider('pose')
        with patch('app.pipeline_diagnostics.time.monotonic',return_value=10):
            d.configure(True,30)
            p.mark('selected',(1,1),1_000_000_000)
            p.mark('preprocess',(1,1),1_050_000_000)
            p.mark('accepted',at=p.started_ns+200_000_000)
            s=p.snapshot()
            self.assertEqual(s['durations']['selected_to_preprocess']['histogram'][5],1)
            self.assertEqual(s['durations']['accepted_interval']['sum_ns'],200_000_000)
        with patch('app.pipeline_diagnostics.time.monotonic',return_value=41):
            p.mark('submitted',(1,1),1_060_000_000)
            self.assertNotIn('submitted',p.counts)
            self.assertFalse(p.snapshot()['collecting'])
        d.configure(True,30)
        self.assertEqual(p.snapshot()['counts'],{})
        d.configure(False,30)
        self.assertEqual(d.snapshot(),{'enabled':False})

    def test_copy_wrapper_is_dynamic_and_off_does_no_timing(self):
        @timed_copy
        def copy(): return 7
        diagnostics.configure(False,1)
        self.assertEqual(copy(),7)
        with self.assertRaises(ValueError): diagnostics.configure(True,61)


if __name__=='__main__': unittest.main()
