"""Fail-closed access to eligible UDE development cutouts in a verified archive.

The source taxonomy is from the UDE dataset; it has not been independently
adjudicated against Academy taxonomy. Bounding crops can contain other diatoms,
and this reader supplies neither instance masks nor background labels.
"""
from __future__ import annotations
import csv,hashlib,io,json,re,zipfile
from pathlib import Path
from PIL import Image
ROOT=Path(__file__).resolve().parent.parent
DEFAULT_ARCHIVE=ROOT/'datasets/r112-ude-full/ude-2024.zip'
DEFAULT_LEDGER=ROOT/'results/r112/ude-sampling-metadata/exposure-ledger.csv'
DEFAULT_REPORT=ROOT/'results/r112/ude-sampling-metadata/exposure-report.json'
DEFAULT_VERIFICATION=ROOT/'results/r112/ude-sampling-metadata/archive-verification.json'
PREFIX='UDE Diatoms in the Wild 2024/images/'
PUBLISHED_MD5='4b46497fb17693aa361e59a0fc91c8bf'
def sha256(path:Path)->str:
 h=hashlib.sha256()
 with path.open('rb') as f:
  for block in iter(lambda:f.read(1024*1024),b''):h.update(block)
 return h.hexdigest()
def source_name_flags(genus:str,species:str)->list[str]:
 """Flag literal uncertainty; this does not perform taxonomic reconciliation."""
 flags=[];name=species.strip();g=genus.strip()
 if name in ('','None'):flags.append('genus_only_or_missing')
 if re.search(r'\b(?:sp|spp|cf|aff)\s*\.',name,re.I):flags.append('qualified_or_morphotype')
 if any(c in name for c in '()='):flags.append('alternate_name_syntax')
 if name and name!='None' and g and name.split()[0].casefold()!=g.casefold():flags.append('genus_string_mismatch')
 return flags
class UDEDevelopmentArchive:
 """Read only prior-development components; protected or unmatched rows fail closed."""
 def __init__(self,archive=DEFAULT_ARCHIVE,ledger=DEFAULT_LEDGER,report=DEFAULT_REPORT,verification=DEFAULT_VERIFICATION,*,expected_md5=PUBLISHED_MD5):
  self.archive=Path(archive);ledger=Path(ledger);report=Path(report);verification=Path(verification)
  if self.archive.name.endswith('.partial'):raise ValueError('Partial archives cannot be used')
  d=json.loads(verification.read_text());r=json.loads(report.read_text())
  if d.get('format')!='r112-ude-full-archive-v1' or r.get('format')!='r112-ude-exposure-ledger-v1':raise ValueError('Unsupported verification or ledger report')
  if self.archive.stat().st_size!=d['bytes'] or sha256(self.archive)!=d['computed_sha256'] or d['computed_md5']!=d['published_md5'] or d['published_md5']!=expected_md5 or d.get('duplicate_member_names')!=0:raise ValueError('Archive verification mismatch')
  if sha256(ledger)!=r['ledger_sha256']:raise ValueError('Exposure ledger verification mismatch')
  self.rows={}
  with ledger.open(newline='',encoding='utf-8') as f:
   for row in csv.DictReader(f):
    ident=row['annotation_id']
    if not ident or ident in self.rows:raise ValueError('Invalid or duplicate annotation ID')
    self.rows[ident]=row
  if len(self.rows)!=r['metadata_rows']:raise ValueError('Ledger row count mismatch')
  self._zip=zipfile.ZipFile(self.archive,'r')
 def close(self):self._zip.close()
 def __enter__(self):return self
 def __exit__(self,*args):self.close()
 def read(self,annotation_id:str,*,require_plain_species:bool=False)->dict:
  row=self.rows[str(annotation_id)]
  if row['exposure_status']!='prior_development':raise PermissionError('Source location is reserved, unmatched, conflicted, or not cleared for development')
  flags=source_name_flags(row['genus'],row['species'])
  if require_plain_species and flags:raise ValueError('Source name has unresolved taxonomic flags or lacks a species label')
  name=row['cutout_filename']
  if not name or '/' in name or '\\' in name or name in ('.','..'):raise ValueError('Invalid source member name')
  info=self._zip.getinfo(PREFIX+name)
  if info.is_dir() or not 0<info.file_size<=4*1024*1024:raise ValueError('Unexpected crop size')
  blob=self._zip.read(info) # CRC-32 checked by zipfile
  image=Image.open(io.BytesIO(blob))
  if image.format!='PNG' or image.width*image.height>16_000_000:raise ValueError('Unexpected image format or dimensions')
  image=image.convert('L');image.load()
  return {'image':image,'annotation_id':str(annotation_id),'source_name':row['species'],'source_genus':row['genus'],'source_name_flags':flags,'source_taxonomy_status':'source dataset label; not independently adjudicated','source_slide':row['image_filename'],'site_component':row['site_component'],'exposure_status':row['exposure_status'],'source_annotation_shape':row['annotation_shape'],'archive_member_sha256':hashlib.sha256(blob).hexdigest(),'archive_member_crc32':f'{info.CRC:08x}','source_um_per_pixel_xy':[.09,.09],'mask_status':'no verified instance mask','background_status':'unknown; crop can contain other organisms'}
