"""Bounded native-resolution RGB extraction from tiled NDPI focal planes.

Requires optional tifffile and imagecodecs. File integrity and provenance must
be checked separately before calling this module. No resampling is performed.
"""
from pathlib import Path
import math
import numpy as np
import tifffile

def crop_ndpi(path,x,y,width,height):
    """Return focal-plane stack (Z,Y,X,3) using bounded JPEG tile reads.

    Only NDPI series with a ZYXS uint8 RGB highest-resolution series and
    independently decodable JPEG tiles are supported. The expected source file
    should be verified against its published hash before opening.
    """
    if any(type(v) is not int for v in (x,y,width,height)) or min(x,y)<0 or min(width,height)<=0:
        raise ValueError('Invalid crop coordinates')
    path=Path(path);size=path.stat().st_size
    with tifffile.TiffFile(path) as tif, path.open('rb') as fd:
        if not tif.is_ndpi or not tif.series:raise ValueError('Expected NDPI input')
        series=tif.series[0]
        if series.axes!='ZYXS' or len(series.shape)!=4 or series.shape[-1]!=3 or series.dtype!=np.uint8:
            raise ValueError('Expected ZYXS uint8 RGB focal stack')
        depth,h,w,_=series.shape
        if x+width>w or y+height>h:raise ValueError('Crop outside image')
        pages=[page for page in tif.pages if page.shape==(h,w,3)]
        if len(pages)!=depth:raise ValueError('Unexpected full-resolution plane count')
        output=np.zeros((depth,height,width,3),dtype='uint8')
        for z,page in enumerate(pages):
            if not page.is_tiled or not page.tilewidth or not page.tilelength or not page.jpegheader:
                raise ValueError('Unsupported NDPI tile organization')
            tw,th=int(page.tilewidth),int(page.tilelength);cols=math.ceil(w/tw);rows=math.ceil(h/th)
            if len(page.dataoffsets)!=cols*rows:raise ValueError('Unexpected tile count')
            for ty in range(y//th,(y+height-1)//th+1):
                for tx in range(x//tw,(x+width-1)//tw+1):
                    index=ty*cols+tx;offset=int(page.dataoffsets[index]);length=int(page.databytecounts[index])
                    if offset<0 or length<=0 or length>16_000_000 or offset+length>size:raise ValueError('Invalid tile bounds')
                    fd.seek(offset);raw=fd.read(length)
                    if len(raw)!=length:raise OSError('Truncated tile')
                    tile,pos,_=page.decode(raw,index,jpegtables=page.jpegtables,jpegheader=page.jpegheader)
                    if tile is None or tile.shape!=(1,th,tw,3) or pos[2]!=ty*th or pos[3]!=tx*tw:raise ValueError('Unexpected decoded tile')
                    left=max(x,tx*tw);top=max(y,ty*th);right=min(x+width,(tx+1)*tw,w);bottom=min(y+height,(ty+1)*th,h)
                    output[z,top-y:bottom-y,left-x:right-x]=tile[0,top-ty*th:bottom-ty*th,left-tx*tw:right-tx*tw]
        return output
