"""Synthetic matching-page package integrity checks."""
import hashlib
import json
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path

ROOT=Path(__file__).resolve().parents[2]


def sha(path):return hashlib.sha256(path.read_bytes()).hexdigest()


class CollectEvidenceTest(unittest.TestCase):
    def setUp(self):
        self.temp=tempfile.TemporaryDirectory();self.root=Path(self.temp.name);self.page=self.root/'page';self.page.mkdir()
        proto={'format':'diatom-frozen-field-protocol-v1','fields':[{'id':'f','sample_id':'test'}],'development_sample_ids':['train'],
               'matching_rule_id':'synthetic-rule','taxonomy_version':'synthetic-taxonomy'};self.protocol=self.write('protocol.json',proto)
        pred={'format':'diatom-frozen-field-predictions-v1','protocol_sha256':sha(self.protocol),'field_id':'f','sample_id':'test','field_image_sha256':'x','predictions':[]};self.pred=self.write('pred.json',pred)
        ref={'format':'diatom-independent-field-reference-v1','protocol_sha256':sha(self.protocol),'field_id':'f','sample_id':'test',
             'field_image_sha256':'x','exhaustive':True,'reference_status':'expert_adjudicated','reviewer_role':'expert','reviewer_id':'synthetic','references':[]};self.ref=self.write('reference.json',ref)
        (self.page/'asset.png').write_bytes(b'synthetic image bytes');display={'field_id':'f','sample_id':'test','protocol_sha256':sha(self.protocol),
            'reference_sha256':sha(self.ref),'predictions_sha256':sha(self.pred),'prediction_ids':[],'references':[],'asset_sha256':{'asset.png':sha(self.page/'asset.png')}}
        (self.page/'index.html').write_text('<script>const payload='+json.dumps(display)+', key="test";</script>')
        match={'format':'diatom-field-matches-v1','display':display,'reviewer_role':'expert','reviewer_id':'synthetic','matches':[]};self.matches=self.write('matches.json',match)

    def tearDown(self):self.temp.cleanup()
    def write(self,name,value):
        path=self.root/name;path.write_text(json.dumps(value));return path
    def collect(self):
        return subprocess.run([sys.executable,str(ROOT/'diatom_pilot/collect_field_matches.py'),'--protocol',str(self.protocol),'--reference',str(self.ref),
            '--predictions',str(self.pred),'--matches',str(self.matches),'--matching-page',str(self.page),'--output',str(self.root/'out.json')],capture_output=True,text=True)
    def test_unchanged_display_is_accepted(self):
        result=self.collect();self.assertEqual(result.returncode,0,result.stderr)
    def test_changed_display_image_is_rejected(self):
        (self.page/'asset.png').write_bytes(b'changed');result=self.collect();self.assertNotEqual(result.returncode,0)
        self.assertIn('Matching page image hash mismatch',result.stderr)


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