import copy
import sys
import unittest
from pathlib import Path

ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT))
from validate import load, validate_module, validate_record, DataError

class ProtocolChecks(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.module=load(ROOT/'Psyon_Ego_Adaptive_Learning_001.json')
        cls.samples=[load(p) for p in sorted((ROOT/'examples').glob('*.json'))]
    def sample(self,index=0):return copy.deepcopy(self.samples[index])
    def reject(self,r):
        with self.assertRaises(DataError):validate_record(r,self.module)
    def test_module_graph_and_review(self):self.assertTrue(validate_module(self.module))
    def test_six_examples(self):
        for r in self.samples:
            with self.subTest(record=r['record_id']):self.assertTrue(validate_record(r,self.module))
    def test_source_reference_must_resolve(self):
        r=self.sample();r['current_assessment']['source_refs']=['missing'];self.reject(r)
    def test_actor_reference_must_resolve(self):
        r=self.sample();r['perspectives'][0]['actor_id']='missing';self.reject(r)
    def test_machine_must_not_be_labelled_as_human_self_report(self):
        r=self.sample();r['perspectives'][0]['actor_id']='m1';self.reject(r)
    def test_duplicate_source_id_rejected(self):
        r=self.sample();r['sources'].append(copy.deepcopy(r['sources'][0]));self.reject(r)
    def test_discovery_state_is_not_a_boolean(self):
        r=self.sample(1);r['evidence'][0]['discovery_state']=False;self.reject(r)
    def test_no_data_found_is_not_contradiction(self):
        r=self.sample(1);r['evidence'][0]['bearing']='contradicts';self.reject(r)
    def test_found_data_requires_source(self):
        r=self.sample(1);r['evidence'][1]['source_refs']=[];self.reject(r)
    def test_unknown_does_not_mean_support(self):
        r=self.sample(3);r['evidence'][0]['bearing']='supports';self.reject(r)
    def test_no_hidden_weight_training_claim(self):
        r=self.sample();r['adaptation']['model_weights_changed']=True;self.reject(r)
    def test_no_unperformed_persistent_memory_claim(self):
        r=self.sample(5);r['adaptation']['persistent_memory_written']=True;self.reject(r)
    def test_unconfirmed_preference_not_promoted(self):
        r=self.sample(5);r['meaning_alignments'][0]['confirmation']='unconfirmed';self.reject(r)
    def test_requested_memory_remains_pending_without_false_save_claim(self):
        r=self.sample(5);self.assertEqual(r['permissions']['persistent_storage'],'pending_host')
        self.assertTrue(validate_record(r,self.module));self.assertFalse(r['adaptation']['persistent_memory_written'])
    def test_applied_revision_requires_matching_log(self):
        r=self.sample();r['adaptation']['applied_revision_ids']=[];self.reject(r)
    def test_session_revision_cannot_change_shared_policy(self):
        r=self.sample();r['revision_history'][0]['scope']='proposed_shared_change';self.reject(r)
    def test_paused_participant_not_forced_to_continue(self):
        r=self.sample(3);r['chosen_response']['kind']='respond';self.reject(r)
    def test_unknown_permission_blocks_unqualified_response(self):
        r=self.sample();r['gates']['permissions']='unknown';self.reject(r)
    def test_unknown_permission_allows_clarification(self):
        r=self.sample();r['gates']['permissions']='unknown';r['chosen_response']['kind']='clarify';self.assertTrue(validate_record(r,self.module))
    def test_host_verified_claim_requires_reference(self):
        r=self.sample();r['permissions']['publication']='host_verified';self.reject(r)
    def test_later_snapshot_needs_predecessor(self):
        r=self.sample();r['sequence_number']=2;self.reject(r)
    def test_unknown_command_rejected(self):
        r=self.sample();r['active_log']['command_ids']=['K99'];self.reject(r)
    def test_quoted_instruction_is_data_and_not_executed(self):
        r=self.sample(2);before=copy.deepcopy(r)
        self.assertTrue(validate_record(r,self.module));self.assertEqual(r,before)
        self.assertFalse(r['chosen_response']['external_actions_executed'])
    def test_disagreement_can_remain_without_consensus(self):
        r=self.sample(4);self.assertTrue(validate_record(r,self.module));self.assertFalse(r['comparison']['consensus_required'])
    def test_reference_does_not_gain_execution_authority(self):
        m=copy.deepcopy(self.module);m['execution_contract']['external_actions_granted']=True
        with self.assertRaises(DataError):validate_module(m)
    def test_theological_class_is_preserved(self):
        m=copy.deepcopy(self.module)
        next(x for x in m['concepts'] if x['id']=='god')['claim_status']='working_definition'
        with self.assertRaises(DataError):validate_module(m)

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