"""An unsorted, multi-block source must be fully scanned, not binary searched."""
import io,zipfile,tempfile,pathlib,random,types,unittest.mock,json,urllib.request,zlib
import sys
sys.path.insert(0,str(pathlib.Path(__file__).resolve().parent / "upstream"))
from full_scan_zip import scan
rng=random.Random(20261112);header=b'MARKERNAME\tCHR\tPOS\tNEA\tEA\tEAF\tBETA\tSE\tP\tQ\tN_Studies'
rows=[]
for j,pos in enumerate(rng.sample(range(43000000,48000000),180000)):
 chrom=19 if j%3 else 1
 rows.append(('%d:%d:G:C\t%d\t%d\tG\tC\t.2\t.001\t.01\t.92\t.8\t26'%(chrom,pos,chrom,pos)).encode())
# This mimics the real release's independently ordered blocks and exceeds one read block.
blocks=[sorted(rows[j:j+60000]) for j in range(0,len(rows),60000)];source=header+b'\n'+b'\n'.join(sum(blocks,[]))+b'\n';assert len(source)>8*1024*1024
buf=io.BytesIO()
with zipfile.ZipFile(buf,'w',compression=zipfile.ZIP_STORED) as z:z.writestr('synthetic.tsv',source)
archive=buf.getvalue();z=zipfile.ZipFile(io.BytesIO(archive));info=z.getinfo('synthetic.tsv')
remote=types.SimpleNamespace(url='https://example.invalid/test',source='synthetic',size=len(archive),etag='test',read_at=lambda a,n:archive[a:a+n])
class Response(io.BytesIO):
 status=206
 def __init__(self,b,a,end):super().__init__(b);self.headers={'Content-Range':'bytes %d-%d/%d'%(a,end,len(archive))}
def open_fake(req,**kw):
 a,end=map(int,req.headers['Range'].split('=')[1].split('-'));return Response(archive[a:end+1],a,end)
with tempfile.TemporaryDirectory() as d,unittest.mock.patch.object(urllib.request,'urlopen',open_fake):
 out=pathlib.Path(d)/'region.tsv';meta=scan('synthetic',remote,info,44668207,46683722,out)
 expected=sorted([r for r in rows if r.split(b'\t')[1]==b'19' and 44668207<=int(r.split(b'\t')[2])<=46683722],key=lambda r:(int(r.split(b'\t')[2]),r.split(b'\t')[0]))
 assert out.read_bytes()==header+b'\n'+b'\n'.join(expected)+b'\n'
 assert meta['global_lexicographic_inversions']>0 and meta['crc_verified']
 info.CRC^=1
 try:scan('synthetic',remote,info,44668207,46683722,pathlib.Path(d)/'bad.tsv')
 except ValueError as e:assert 'CRC' in str(e)
 else:raise AssertionError('A corrupted source CRC was accepted')
print('PASS: full scan of 180,000 independently shuffled/block-sorted rows matches an independent full-data oracle; wrong CRC rejected.')
