"""Fetch one indexed ZIP member with validated local header, length and CRC."""
import argparse,hashlib,json,struct,zlib
from pathlib import Path
from r44_menne_archive import Remote,OUT

def fetch(entry):
 src=Remote();src.seek(entry['header_offset']);header=src.read(30)
 if len(header)!=30:raise ValueError('Truncated ZIP local header')
 sig,version,flags,method,tm,dt,crc,compressed,size,nlen,xlen=struct.unpack('<IHHHHHIIIHH',header)
 if sig!=0x04034b50 or flags&1 or method not in (0,8):raise ValueError('Unsupported ZIP member')
 name=src.read(nlen);extra=src.read(xlen)
 if name.decode('utf-8' if flags&0x800 else 'cp437')!=entry['name']:raise ValueError('ZIP member name mismatch')
 payload=src.read(entry['compressed_bytes'])
 if len(payload)!=entry['compressed_bytes']:raise ValueError('Truncated compressed member')
 data=zlib.decompress(payload,-15) if method==8 else payload
 if len(data)!=entry['bytes'] or f'{zlib.crc32(data)&0xffffffff:08x}'!=entry['crc32']:raise ValueError('ZIP size or CRC mismatch')
 return data

def main():
 p=argparse.ArgumentParser(description=__doc__);p.add_argument('--member',required=True);p.add_argument('--output',type=Path,required=True);a=p.parse_args()
 if a.output.exists():raise FileExistsError('Do not overwrite downloaded evidence')
 entries=json.loads((OUT/'archive-index.json').read_text())['entries'];match=[e for e in entries if e['name']==a.member]
 if len(match)!=1:raise ValueError('Member not uniquely found')
 data=fetch(match[0]);a.output.parent.mkdir(parents=True,exist_ok=True);a.output.write_bytes(data)
 print('Verified',a.member,'bytes',len(data),'sha256',hashlib.sha256(data).hexdigest(),flush=True)
if __name__=='__main__':main()
