"""Enforce archive integrity and exclusion of reserved site groups."""
import csv,hashlib,io,json,tempfile,unittest,zipfile
from pathlib import Path
from PIL import Image
from diatom_pilot.ude_development_archive import UDEDevelopmentArchive,PREFIX,source_name_flags
class UDEDevelopmentArchiveTests(unittest.TestCase):
 def setUp(self):
  self.tmp=tempfile.TemporaryDirectory();self.d=Path(self.tmp.name);self.archive=self.d/'archive.zip';self.ledger=self.d/'ledger.csv';self.report=self.d/'report.json';self.verify=self.d/'verify.json';buf=io.BytesIO();Image.new('L',(12,7),127).save(buf,format='PNG')
  with zipfile.ZipFile(self.archive,'w') as z:z.writestr(PREFIX+'one.png',buf.getvalue())
  fields=['annotation_id','cutout_filename','genus','species','image_filename','site_component','exposure_status','annotation_shape'];self.rows=[{'annotation_id':'1','cutout_filename':'one.png','genus':'Navicula','species':'Navicula gregaria','image_filename':'x.tif','site_component':'site-1','exposure_status':'prior_development','annotation_shape':'Rectangle'},{'annotation_id':'2','cutout_filename':'one.png','genus':'Navicula','species':'Navicula gregaria','image_filename':'y.tif','site_component':'site-2','exposure_status':'candidate_unseen_location','annotation_shape':'Rectangle'},{'annotation_id':'3','cutout_filename':'one.png','genus':'Navicula','species':'None','image_filename':'z.tif','site_component':'site-3','exposure_status':'prior_development','annotation_shape':'Rectangle'}]
  with self.ledger.open('w',newline='') as f:w=csv.DictWriter(f,fieldnames=fields);w.writeheader();w.writerows(self.rows)
  self.report.write_text(json.dumps({'format':'r112-ude-exposure-ledger-v1','metadata_rows':3,'ledger_sha256':hashlib.sha256(self.ledger.read_bytes()).hexdigest()}));self.verify.write_text(json.dumps({'format':'r112-ude-full-archive-v1','bytes':self.archive.stat().st_size,'published_md5':'test','computed_md5':'test','computed_sha256':hashlib.sha256(self.archive.read_bytes()).hexdigest(),'duplicate_member_names':0}))
 def tearDown(self):self.tmp.cleanup()
 def open(self):return UDEDevelopmentArchive(self.archive,self.ledger,self.report,self.verify,expected_md5="test")
 def test_reads_development_without_inventing_mask(self):
  with self.open() as a:
   r=a.read('1',require_plain_species=True);self.assertEqual(r['image'].size,(12,7));self.assertEqual(r['background_status'],'unknown; crop can contain other organisms');self.assertEqual(r['mask_status'],'no verified instance mask')
 def test_reserved_location_cannot_be_read(self):
  with self.open() as a:
   with self.assertRaises(PermissionError):a.read('2')
 def test_all_reserved_and_unmatched_statuses_rejected(self):
  with self.open() as a:
   for status in ('legacy_reserved','legacy_reserved_conflict','candidate_unseen_location','unmatched_slide_quarantine','unexpected'):
    a.rows['1']['exposure_status']=status
    with self.subTest(status=status):
     with self.assertRaises(PermissionError):a.read('1')
 def test_wrong_publisher_checksum_is_rejected(self):
  with self.assertRaises(ValueError):UDEDevelopmentArchive(self.archive,self.ledger,self.report,self.verify)
 def test_species_requirement_blocks_genus_only(self):
  with self.open() as a:
   with self.assertRaises(ValueError):a.read('3',require_plain_species=True)
 def test_archive_modification_rejected(self):
  self.archive.write_bytes(self.archive.read_bytes()+b'x')
  with self.assertRaises(ValueError):self.open()
 def test_ledger_modification_rejected(self):
  self.ledger.write_text(self.ledger.read_text()+'\n')
  with self.assertRaises(ValueError):self.open()
 def test_literal_name_flags_do_not_resolve_synonyms(self):
  self.assertIn('alternate_name_syntax',source_name_flags('Cyclotella','Cyclotella x (Stephanocyclus y)'));self.assertIn('qualified_or_morphotype',source_name_flags('Gomphonema','Gomphonema sp. 1'))
if __name__=='__main__':unittest.main()
