from fractions import Fraction as F
import hashlib
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
import bounded_algorithms as lab


class BoundedAlgorithmsTests(unittest.TestCase):
    def test_first_hit_is_not_largest_or_sorted_position(self):
        self.assertTrue(hasattr(lab,'first_at_least'),'finite search is not implemented')
        self.assertEqual(lab.first_at_least([4,9,7,15,13],12),
                         {'index':3,'value':15,'comparisons':4,'length':5})

    def test_search_handles_no_hit_empty_and_exact_threshold(self):
        self.assertEqual(lab.first_at_least([],0),{'index':None,'value':None,'comparisons':0,'length':0})
        self.assertEqual(lab.first_at_least([1,2],3),{'index':None,'value':None,'comparisons':2,'length':2})
        self.assertEqual(lab.first_at_least([5,9],5)['index'],0)

    def test_search_validates_even_after_an_early_hit(self):
        for values,t in [([3,True],2),([3,-1],2),([3,1.5],2),([3,1000001],2),
                         ([1]*1001,1),((1,2),1),([1],True),([1],-1)]:
            with self.subTest(values=str(values)[:30]),self.assertRaises(ValueError):
                lab.first_at_least(values,t)

    def test_halving_plan_uses_midpoint_error_not_full_width(self):
        self.assertEqual(lab.halvings_needed(1,F(1,128)),6)
        self.assertEqual(lab.halvings_needed(1,F(1,1000)),9)
        self.assertEqual(lab.halvings_needed(1,F(1,2)),0)

    def test_worked_bracket_and_error_certificate(self):
        r=lab.bisect_response(5,1,2,F(1,128),6)
        self.assertEqual(r['status'],'tolerance_met'); self.assertTrue(r['converged'])
        self.assertEqual(r['halvings'],6)
        self.assertEqual((r['lower'],r['upper'],r['candidate'],r['error_bound']),
                         ('23/16','93/64','185/128','1/128'))

    def test_budget_failure_keeps_a_valid_but_wide_bracket(self):
        r=lab.bisect_response(5,1,2,F(1,128),4)
        self.assertEqual(r['status'],'budget_exhausted'); self.assertFalse(r['converged'])
        self.assertEqual((r['lower'],r['upper'],r['candidate'],r['error_bound']),
                         ('23/16','3/2','47/32','1/32'))
        self.assertEqual(r['halvings'],4)

    def test_exact_endpoint_and_candidate_do_not_require_cuts(self):
        for target,lo,hi,root in [(3,1,2,'1'),(8,1,2,'2'),(8,1,3,'2')]:
            r=lab.bisect_response(target,lo,hi,F(1,1000),0)
            self.assertEqual(r['status'],'exact_root'); self.assertTrue(r['converged'])
            self.assertEqual(r['candidate'],root); self.assertEqual(r['error_bound'],'0')
            self.assertEqual(r['halvings'],0)

    def test_zero_budget_and_sufficient_initial_error_are_distinct(self):
        r=lab.bisect_response(5,1,2,F(1,128),0)
        self.assertEqual(r['status'],'budget_exhausted')
        r=lab.bisect_response(5,1,2,F(1,2),0)
        self.assertEqual(r['status'],'tolerance_met'); self.assertEqual(r['halvings'],0)

    def test_unbracketed_target_is_rejected(self):
        for target,lo,hi in [(5,2,3),(5,0,1)]:
            with self.assertRaises(ValueError):lab.bisect_response(target,lo,hi,F(1,100),10)

    def test_invalid_rationals_order_tolerance_and_budget_are_rejected(self):
        good=[5,1,2,F(1,128),6]
        for position,bad in [(0,True),(0,5.0),(0,10201),(0,-1),(0,F(1,10**9+1)),
                             (1,-1),(2,101),(1,2),(3,0),(3,-1),(3,101),
                             (3,F(1,10**9+1)),(4,-1),(4,201),(4,True),(4,2.0)]:
            args=good.copy();args[position]=bad
            with self.subTest(args=args),self.assertRaises(ValueError):lab.bisect_response(*args)
        for w,t in [(0,F(1,10)),(-1,F(1,10)),(101,F(1,10)),(1,0),(1,.1)]:
            with self.assertRaises(ValueError):lab.halvings_needed(w,t)

    def test_trace_preserves_signs_nestedness_and_halves_width(self):
        r=lab.bisect_response(7,1,2,F(1,256),7)
        self.assertEqual(len(r['trace']),7)
        self.assertEqual((r['lower'],r['upper'],r['candidate']),('117/64','235/128','469/256'))
        for row in r['trace']:
            a,b,m=map(F,[row['old_lower'],row['old_upper'],row['midpoint']])
            c,d=map(F,[row['new_lower'],row['new_upper']])
            self.assertEqual(m,(a+b)/2);self.assertEqual(d-c,(b-a)/2)
            self.assertTrue(a<=c<d<=b)
            self.assertLessEqual(c*c+2*c-7,0);self.assertGreaterEqual(d*d+2*d-7,0)

    def test_float_spacing_demo_is_stagnation_not_a_root_solver(self):
        r=lab.stagnation_demo()
        self.assertFalse(r['can_shrink']);self.assertEqual(r['midpoint'],r['lower'])
        self.assertGreater(r['half_width'],r['requested_tolerance'])

    def test_new_run_and_repeat_preserve_sources_and_hashes(self):
        with tempfile.TemporaryDirectory() as tmp:
            a,b=Path(tmp)/'a',Path(tmp)/'b'
            lab.run_lab(a);lab.run_lab(b)
            self.assertEqual((a/'report.json').read_bytes(),(b/'report.json').read_bytes())
            self.assertEqual((a/'bounded_algorithms.py').read_bytes(),Path(lab.__file__).read_bytes())
            manifest=json.loads((a/'run.json').read_text())
            self.assertEqual(manifest['status'],'complete')
            for name,digest in manifest['files'].items():
                self.assertEqual(hashlib.sha256((a/name).read_bytes()).hexdigest(),digest)

    def test_existing_output_is_not_reused(self):
        with tempfile.TemporaryDirectory() as tmp:
            out=Path(tmp)/'out';out.mkdir();(out/'keep').write_text('unique')
            with self.assertRaises(FileExistsError):lab.run_lab(out)
            self.assertEqual([p.name for p in out.iterdir()],['keep'])
            self.assertEqual((out/'keep').read_text(),'unique')

    def test_partial_failure_is_preserved_without_completion(self):
        with tempfile.TemporaryDirectory() as tmp:
            out=Path(tmp)/'out';original=Path.open
            def failure(path,*args,**kwargs):
                if path==out/'bounded_algorithms.py':raise OSError('injected late failure')
                return original(path,*args,**kwargs)
            with patch.object(Path,'open',failure):
                with self.assertRaises(OSError):lab.run_lab(out)
            self.assertTrue((out/'report.json').exists());self.assertFalse((out/'run.json').exists())

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