"""Synthetic integrity checks for the visual expert-matching evidence."""
import hashlib
import json
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from PIL import Image

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


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


class MatchEvidenceTest(unittest.TestCase):
    def setUp(self):
        self.temp=tempfile.TemporaryDirectory();self.root=Path(self.temp.name);self.bundle=self.root/'field';self.bundle.mkdir()
        image=Image.new('RGB',(16,16),(100,120,140));image.save(self.bundle/'field.png');image.save(self.bundle/'plane.png');image.crop((2,2,10,10)).save(self.bundle/'crop.png')
        protocol={'format':'diatom-frozen-field-protocol-v1','candidate_policy':'all_original_detector_candidates','fields':[{'id':'f','sample_id':'test'}]}
        self.protocol=self.write('protocol.json',protocol)
        bundle={'bundle_id':'synthetic','slide':'scan.tif','slide_size_bytes':1_000_000_000,'origin_xy':[0,0],'size':16,'z':0,'field_image':'field.png'};(self.bundle/'bundle.json').write_text(json.dumps(bundle))
        focus={'format':'diatom-focus-planes-v1','bundle_id':'synthetic','planes':[{'z':0,'image':'plane.png','sha256':sha(self.bundle/'plane.png')}]};(self.bundle/'focus-planes.json').write_text(json.dumps(focus))
        pred={'format':'diatom-frozen-field-predictions-v1','protocol_sha256':sha(self.protocol),'candidate_policy':protocol['candidate_policy'],
              'bundle_sha256':sha(self.bundle/'bundle.json'),'bundle_id':'synthetic','field_id':'f','sample_id':'test',
              'field_image_sha256':sha(self.bundle/'field.png'),'source_manifest_sha256':{},'predictions':[{'id':'p','box':[2,2,10,10],
              'plane_z':0,'source_plane_sha256':sha(self.bundle/'field.png'),'crop':'crop.png','source_crop_sha256':sha(self.bundle/'crop.png'),
              'mask':None,'source_mask_sha256':None}]};self.predictions=self.write('pred.json',pred)
        ref={'format':'diatom-independent-field-reference-v1','protocol_sha256':sha(self.protocol),'field_id':'f','sample_id':'test',
             'reference_status':'expert_adjudicated','reviewer_role':'expert','reviewer_id':'synthetic-only','exhaustive':True,
             'field_image_sha256':sha(self.bundle/'field.png'),'references':[{'id':'r','field_xy':[5,5],'z':0}]};self.reference=self.write('reference.json',ref)

    def tearDown(self):self.temp.cleanup()
    def write(self,name,value):
        path=self.root/name;path.write_text(json.dumps(value));return path
    def make_page(self):
        return subprocess.run([sys.executable,str(ROOT/'diatom_pilot/make_field_matching_page.py'),'--protocol',str(self.protocol),
            '--predictions',str(self.predictions),'--reference',str(self.reference),'--bundle',str(self.bundle),
            '--output',str(self.root/'page')],capture_output=True,text=True)

    def test_valid_evidence_renders(self):
        result=self.make_page();self.assertEqual(result.returncode,0,result.stderr)
        self.assertTrue((self.root/'page/proposal-0001-z000.png').exists())

    def test_changed_crop_is_rejected(self):
        Image.new('RGB',(8,8),'magenta').save(self.bundle/'crop.png')
        result=self.make_page();self.assertNotEqual(result.returncode,0);self.assertIn('Proposal crop hash mismatch',result.stderr)

    def test_changed_focal_plane_is_rejected(self):
        Image.new('RGB',(16,16),'magenta').save(self.bundle/'plane.png')
        result=self.make_page();self.assertNotEqual(result.returncode,0);self.assertIn('Focal plane hash mismatch',result.stderr)

    def test_reference_from_unscored_scan_requires_matching_planes(self):
        ref=json.loads(self.reference.read_text());ref['display_provenance']={'format':'diatom-reference-page-v1','source_kind':'unscored_scan',
            'protocol_sha256':sha(self.protocol),'field_id':'f','sample_id':'test','field_image_sha256':sha(self.bundle/'field.png'),
            'slide':'scan.tif','slide_size_bytes':1_000_000_000,'origin_xy':[0,0],'size':16,'model_z':0,
            'planes':[{'z':0,'image':'plane-000.png','sha256':sha(self.bundle/'plane.png')}]}
        self.reference.write_text(json.dumps(ref));result=self.make_page();self.assertEqual(result.returncode,0,result.stderr)

    def test_reference_from_unscored_scan_rejects_different_planes(self):
        ref=json.loads(self.reference.read_text());ref['display_provenance']={'format':'diatom-reference-page-v1','source_kind':'unscored_scan',
            'protocol_sha256':sha(self.protocol),'field_id':'f','sample_id':'test','field_image_sha256':sha(self.bundle/'field.png'),
            'slide':'scan.tif','slide_size_bytes':1_000_000_000,'origin_xy':[0,0],'size':16,'model_z':0,
            'planes':[{'z':0,'image':'plane-000.png','sha256':'0'*64}]}
        self.reference.write_text(json.dumps(ref));result=self.make_page();self.assertNotEqual(result.returncode,0)
        self.assertIn('Reference scan planes differ',result.stderr)


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