"""Definition, boundary and deliberately wrong-map tests; standard library only."""
import copy
import importlib.util
import json
from pathlib import Path
import unittest

ROOT=Path(__file__).resolve().parent
spec=importlib.util.spec_from_file_location('primary',ROOT/'check.py');checker=importlib.util.module_from_spec(spec);spec.loader.exec_module(checker)
BASE=json.loads((ROOT/'input.json').read_text())

class PrimaryChecks(unittest.TestCase):
    def test_explicit_transition_table_and_minimal_hits(self):
        # Hand-inspectable equations: 3*5+1=16, 3*21+1=64; all following steps halve.
        result=checker.run(BASE)
        a,b=result['records']
        self.assertEqual(a['orbit'],['5','8','4','2','1'])
        self.assertEqual(b['orbit'],['21','32','16','8','4','2','1'])
        self.assertEqual([a['parity_prefix'],b['parity_prefix']],['1000','1000'])
        self.assertEqual([a['first_hit'],b['first_hit']],[4,6])
        self.assertTrue(all('1' not in r['orbit'][:r['first_hit']] for r in result['records']))
        self.assertEqual(result['disposition'],'counterexample')

    def test_start_one_is_zero_steps_and_prefix_continues_the_total_map(self):
        result=checker.run(BASE|{'starts':['1','2']})['records']
        self.assertEqual([r['first_hit'] for r in result],[0,1])
        self.assertEqual([r['parity_prefix'] for r in result],['1010','0101'])
        self.assertEqual(result[0]['orbit'],['1','2','1','2'])

    def test_caps_are_unknown_never_counterexamples_without_complete_witnesses(self):
        for values in [{'max_steps':0},{'max_steps':3},{'max_bits':4}]:
            result=checker.run(BASE|values)
            self.assertEqual(result['disposition'],'unknown')
            self.assertEqual(result['counterexample_pairs'],[])
        result=checker.run(BASE|{'max_steps':4})
        self.assertEqual(result['records'][0]['first_hit'],4)
        self.assertEqual(result['records'][1]['status'],'resource-limit')
        self.assertEqual(result['disposition'],'unknown')
        self.assertEqual(checker.run(BASE|{'max_steps':6})['disposition'],'counterexample')

    def test_equal_inputs_only_establish_no_witness_in_these_inputs(self):
        self.assertEqual(checker.run(BASE|{'starts':['5','5']})['disposition'],'no-counterexample-in-supplied-inputs')

    def test_arbitrary_precision_transition(self):
        n=2**100+1
        self.assertEqual(checker.step(n),(3*n+1)//2)
        self.assertEqual(checker.step(2**100),2**99)

    def test_strict_domain_and_hard_resource_ceilings(self):
        for start in ['0','-1','1.0','01','+5',' 5','1e2',5,True,None,'9'*1235]:
            with self.assertRaises(ValueError):checker.run(BASE|{'starts':[start,'21']})
        for field,value in [('prefix_length',0),('prefix_length',True),('max_steps',-1),('max_steps',10001),('max_bits',4097),('schema',True)]:
            with self.assertRaises(ValueError):checker.run(BASE|{field:value})
        with self.assertRaises(ValueError):checker.run(BASE|{'extra':1})
        with self.assertRaises(ValueError):checker.no_duplicates([('schema',1),('schema',1)])

    def test_mutated_unaccelerated_map_does_not_match_expected_certificate(self):
        original=checker.step
        try:
            checker.step=lambda n:n//2 if n%2==0 else 3*n+1
            result=checker.run(BASE)
            self.assertNotEqual(result['records'][0]['orbit'],['5','8','4','2','1'])
            self.assertNotEqual([r['first_hit'] for r in result['records']],[4,6])
        finally:checker.step=original

    def test_mutated_all_powers_acceleration_does_not_match(self):
        original=checker.step
        def odd_only(n):
            if n%2==0:return n//2
            n=3*n+1
            while n%2==0:n//=2
            return n
        try:
            checker.step=odd_only
            self.assertNotEqual([r['first_hit'] for r in checker.run(BASE)['records']],[4,6])
        finally:checker.step=original

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