"""Create a bounded, edge-covering grid of field jobs for a microscope scan."""
import argparse
import json
import sys
from pathlib import Path

sys.path.insert(0,str(Path(__file__).resolve().parent.parent/'experiments'))
from scan_fields import Stack


def axis_positions(start,length,size,stride):
    """Cover [start,start+length) without leaving a gap at the far edge."""
    if start<0 or length<size or size<1 or not 1<=stride<=size:raise ValueError('Invalid grid axis')
    last=start+length-size
    positions=list(range(start,last+1,stride))
    if positions[-1]!=last:positions.append(last)
    return positions


def main():
    p=argparse.ArgumentParser(description=__doc__);p.add_argument('--slide',type=Path,required=True)
    p.add_argument('--output',type=Path,required=True);p.add_argument('--z',type=int,required=True)
    p.add_argument('--region',type=int,nargs=4,metavar=('X','Y','WIDTH','HEIGHT'),help='Region in native pixels; omit for full image bounds')
    p.add_argument('--size',type=int,default=768);p.add_argument('--stride',type=int,default=512)
    p.add_argument('--max-fields',type=int,default=1000)
    a=p.parse_args()
    if a.output.exists():raise FileExistsError('Refusing to replace existing jobs file')
    if not 1<=a.size<=2048 or not 1<=a.stride<=a.size or a.z<0 or a.max_fields<1:p.error('Invalid size, stride, Z, or field limit')
    if a.slide.stat().st_size<1_000_000_000:raise ValueError('Scan is below the 1 GB completed-file cutoff')
    with Stack(a.slide) as stack:
        width,height,depth=stack.width,stack.height,stack.depth
        if a.z>=depth:raise ValueError('Z plane outside scan')
        x,y,w,h=a.region or [0,0,width,height]
        if min(x,y)<0 or w<a.size or h<a.size or x+w>width or y+h>height:raise ValueError('Region outside scan or smaller than field size')
        # Count before constructing a potentially huge grid.
        nx=(w-a.size+a.stride-1)//a.stride+1;ny=(h-a.size+a.stride-1)//a.stride+1
        if nx*ny>a.max_fields:raise ValueError(f'Grid requires {nx*ny} fields; limit is {a.max_fields}. Narrow the region or explicitly increase --max-fields.')
        xs=axis_positions(x,w,a.size,a.stride);ys=axis_positions(y,h,a.size,a.stride)
        jobs=[{'id':f'tile-r{row:05d}-c{col:05d}','slide':str(a.slide),'x':xx,'y':yy,'z':a.z,'size':a.size}
              for row,yy in enumerate(ys) for col,xx in enumerate(xs)]
        data={'format':'diatom-field-jobs-v1','grid':{'slide_size_bytes':a.slide.stat().st_size,
              'scan_size_xy':[width,height],'region_xywh':[x,y,w,h],'field_size':a.size,'nominal_stride':a.stride,
              'rows':len(ys),'columns':len(xs),'warning':'Adjacent fields may overlap; cross-field deduplication is not implemented.'},'fields':jobs}
    a.output.parent.mkdir(parents=True,exist_ok=True)
    with a.output.open('x') as out:json.dump(data,out,indent=2);out.write('\n')
    print(f'Wrote {len(jobs)} field jobs ({len(ys)} rows × {len(xs)} columns) to {a.output}')


if __name__=='__main__':main()
