"""Turn a downloaded field review into traceable, non-adjudicated specimens."""
import argparse
import hashlib
import json
import math
from pathlib import Path

from PIL import Image,ImageDraw

DECISIONS={'unreviewed','possible','countable','reject','unsure'}
ROLES={'unknown','nonexpert','expert'}


def digest(path):
    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 inside(root,name):
    if not isinstance(name,str) or Path(name).is_absolute():raise ValueError('Expected a relative image path')
    result=(root/name).resolve()
    if not result.is_relative_to(root.resolve()) or not result.is_file():raise ValueError(f'Invalid bundle image: {name}')
    return result


def polygon_mask(points,size):
    if not isinstance(points,list) or len(points)<3:raise ValueError('Outline requires at least three points')
    clean=[]
    for point in points:
        if not isinstance(point,list) or len(point)!=2 or any(not isinstance(x,(int,float)) or isinstance(x,bool) or not math.isfinite(x) for x in point):
            raise ValueError('Invalid outline coordinate')
        x,y=point
        if not 0<=x<size or not 0<=y<size:raise ValueError('Outline coordinate outside field')
        clean.append((round(x),round(y)))
    if len(set(clean))<3:raise ValueError('Outline needs three distinct points')
    area=sum(a[0]*b[1]-b[0]*a[1] for a,b in zip(clean,clean[1:]+clean[:1]))
    if area==0:raise ValueError('Degenerate outline')
    result=Image.new('L',(size,size),0);ImageDraw.Draw(result).polygon(clean,fill=255)
    return result


def main():
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--review',type=Path,required=True);p.add_argument('--bundle',type=Path,required=True)
    p.add_argument('--output',type=Path,required=True)
    p.add_argument('--sample-id',help='Explicit biological sample identifier if missing from review')
    p.add_argument('--reviewer-id',help='Reviewer identifier if missing from review')
    p.add_argument('--reviewer-role',choices=sorted(ROLES),help='Reviewer-reported role if missing from review')
    p.add_argument('--point-crop-radius',type=int,default=128,help='Context crop radius in field pixels for manual points without outlines (default: 128)')
    p.add_argument('--point-proposals',type=Path,help='Directory containing point-mask proposals and masks')
    p.add_argument('--point-choices',type=Path,help='Downloaded point-mask choices JSON')
    args=p.parse_args()
    if args.point_crop_radius<1:raise ValueError('Point crop radius must be positive')
    if bool(args.point_proposals)!=bool(args.point_choices):raise ValueError('Provide both point-proposals and point-choices')
    data=json.loads(args.review.read_text());bundle=json.loads((args.bundle/'bundle.json').read_text())
    if data.get('format')!='diatom-field-review-v1' or data.get('bundle')!=bundle:
        raise ValueError('Review bundle does not exactly match the supplied bundle')
    focus=data.get('focus_planes');split=data.get('split_alternatives');stack=data.get('stack_proposals');tile=data.get('tile_proposals')
    for manifest,name in ((focus,'focus-planes.json'),(split,'split-alternatives.json'),(stack,'stack-proposals.json'),(tile,'tile-proposals.json')):
        if manifest is not None:
            local=json.loads((args.bundle/name).read_text())
            if manifest!=local or manifest.get('bundle_id')!=bundle['bundle_id']:raise ValueError(f'{name} does not match exported review')
    state=data.get('review',{});context=state.get('context') or {}
    def choose(key,override):
        recorded=str(context.get(key) or '').strip()
        if recorded and override and recorded!=override:raise ValueError(f'{key} conflicts with review')
        return recorded or (override or '').strip()
    sample=choose('sample_id',args.sample_id);reviewer=choose('reviewer_id',args.reviewer_id)
    # "unknown" records that the browser reviewer did not specify a role;
    # an explicit later declaration can fill that missing value.
    role=(args.reviewer_role if context.get('reviewer_role')=='unknown' and args.reviewer_role
          else choose('reviewer_role',args.reviewer_role)) or 'unknown'
    coverage=context.get('field_coverage') or 'not_evaluated'
    if not sample or not reviewer:raise ValueError('Explicit sample and reviewer identifiers are required')
    if role not in ROLES:raise ValueError('Invalid reviewer role')
    if coverage not in {'not_evaluated','complete','incomplete'}:raise ValueError('Invalid field coverage value')
    candidates=list(bundle['candidates'])+([] if split is None else split['hypotheses'])+([] if stack is None else stack['proposals'])+([] if tile is None else tile['proposals'])
    byid={c['id']:c for c in candidates}
    if len(byid)!=len(candidates):raise ValueError('Duplicate candidate IDs')
    reviews=state.get('candidates',{});manual=state.get('manual',[])
    if not isinstance(reviews,dict) or not isinstance(manual,list) or set(reviews)-set(byid):raise ValueError('Unexpected candidate review IDs')
    relations=state.get('relations',[]);relation_records=[];relation_pairs=set()
    if not isinstance(relations,list):raise ValueError('Invalid candidate relationships')
    for relation in relations:
        if not isinstance(relation,dict):raise ValueError('Invalid candidate relationship')
        left,right=relation.get('a'),relation.get('b');assessment=relation.get('relation');note=relation.get('note')
        if (not isinstance(left,str) or not isinstance(right,str) or left>=right or left not in byid or right not in byid
            or assessment not in {'same','different','unsure'} or not isinstance(note,str) or (left,right) in relation_pairs):
            raise ValueError('Invalid or duplicate candidate relationship')
        relation_pairs.add((left,right));relation_records.append({'a':left,'b':right,'relation':assessment,'note':note,
            'reviewer_id':reviewer,'reviewer_role':role,'adjudicated':False,'a_proposal':byid[left],'b_proposal':byid[right]})
    size=bundle['size'];origin=bundle['origin_xy'];specimens=[]
    selected_masks={};mask_choice_hash=None
    if args.point_proposals:
        manifest_path=args.point_proposals/'proposals.json';point_data=json.loads(manifest_path.read_text());choices=json.loads(args.point_choices.read_text())
        if (point_data.get('format')!='diatom-point-mask-proposals-v1' or point_data.get('bundle_id')!=bundle['bundle_id']
            or point_data.get('review_sha256')!=digest(args.review) or point_data.get('segmenter_sha256')!=bundle['models']['segmenter_sha256']
            or choices.get('format')!='diatom-point-mask-choices-v1' or choices.get('source_sha256')!=digest(manifest_path)
            or choices.get('source')!=point_data):raise ValueError('Point-mask provenance mismatch')
        mask_review=choices.get('review',{});mask_reviewer=mask_review.get('reviewer');mask_role=mask_review.get('role')
        decisions=mask_review.get('choices');records=point_data.get('records')
        if not isinstance(mask_reviewer,str) or not mask_reviewer.strip() or mask_role not in ROLES or not isinstance(decisions,dict) or not isinstance(records,list):
            raise ValueError('Invalid point-mask reviewer or choices')
        lookup={r['id']:r for r in records}
        if len(lookup)!=len(records) or set(decisions)-set(lookup):raise ValueError('Invalid point-mask IDs')
        for ident,choice in decisions.items():
            if not isinstance(choice,dict) or not isinstance(choice.get('variant'),str) or not isinstance(choice.get('note'),str):raise ValueError('Invalid point-mask choice')
            if not choice['variant']:continue
            record=lookup[ident];variants=[v for v in record['variants'] if v['name']==choice['variant']]
            if len(variants)!=1 or not variants[0].get('mask'):raise ValueError('Selected mask is unavailable')
            selected_masks[ident]=(record,variants[0],choice['note'],mask_reviewer.strip(),mask_role)
        if set(selected_masks)-{f'manual-{i:04d}' for i in range(1,len(manual)+1)}:
            raise ValueError('Selected point-mask ID is absent from the field review')
        mask_choice_hash=digest(args.point_choices)
    if args.output.exists() and any(args.output.iterdir()):raise FileExistsError('Output directory must be empty')
    args.output.mkdir(parents=True,exist_ok=True)
    plane_map={} if focus is None else {p['z']:p for p in focus['planes']}

    def plane(z):
        if not isinstance(z,int) or isinstance(z,bool):raise ValueError('Invalid plane index')
        if z in plane_map:
            item=plane_map[z];path=inside(args.bundle,item['image'])
            if digest(path)!=item['sha256']:raise ValueError('Focal-plane image hash mismatch')
        elif z==bundle['z']:
            path=inside(args.bundle,bundle['field_image'])
        else:raise ValueError(f'No image for plane {z}')
        im=Image.open(path).convert('RGB')
        if im.size!=(size,size):raise ValueError('Unexpected plane dimensions')
        return im

    def add(identifier,review,candidate=None,mark=None):
        decision=review.get('decision') or 'unreviewed'
        if decision not in DECISIONS:raise ValueError(f'Invalid decision for {identifier}')
        label=review.get('species') or '';note=review.get('note') or ''
        if not isinstance(label,str) or not isinstance(note,str):raise ValueError('Taxon and notes must be text')
        taxon_rank=review.get('taxon_rank') or 'unknown';certainty=review.get('identification_certainty') or 'unknown'
        if taxon_rank not in {'unknown','genus','species','other'} or certainty not in {'unknown','tentative','confident','unresolved'}:
            raise ValueError('Invalid taxon rank or identification certainty')
        partial=review.get('partial') or 'unknown';overlap=review.get('overlap') or 'unknown'
        group=review.get('overlap_group') or ''
        if partial not in {'unknown','yes','no'} or overlap not in {'unknown','yes','no'} or not isinstance(group,str):
            raise ValueError('Invalid partial or overlap annotation')
        if (candidate is not None and decision=='unreviewed' and not label and not note and not review.get('outline')
                and partial=='unknown' and overlap=='unknown' and not group.strip()
                and taxon_rank=='unknown' and certainty=='unknown'):return
        item={'id':identifier,'source':'manual' if mark is not None else candidate.get('source','detector'),
              'parent_candidate_id':candidate.get('parent_candidate_id') if candidate else None,
              'decision':decision,'taxon_text':label.strip(),'taxon_rank':taxon_rank,
              'identification_certainty':certainty,'note':note,'adjudicated':False,
              'partial':partial,'overlap':overlap,'overlap_group':group.strip(),
              'annotation_status':'reviewer_reported_expert' if role=='expert' else 'provisional',
              'proposal':candidate,'mark':None,'geometry':None,'crop':None}
        if mark is not None:
            x,y=mark['x'],mark['y'];z=mark.get('z',bundle['z'])
            if not isinstance(x,(int,float)) or not isinstance(y,(int,float)) or not 0<=x<size or not 0<=y<size:raise ValueError('Invalid manual mark')
            plane(z)
            item['mark']={'field_xy':[x,y],'slide_xy':[origin[0]+x,origin[1]+y],'z':z}
        if mark is not None and identifier in selected_masks and review.get('outline'):
            raise ValueError('A manual mark cannot use both a reviewer outline and a selected model mask')
        if review.get('outline'):
            z=review.get('outline_z',bundle['z']);mask=polygon_mask(review['outline'],size)
            item['geometry']={'kind':'reviewer_polygon','z':z,'field_xy':review['outline']}
        elif mark is not None and identifier in selected_masks:
            record,variant,mask_note,mask_reviewer,mask_role=selected_masks[identifier]
            z=mark.get('z',bundle['z'])
            if (record.get('x'),record.get('y'),record.get('z'))!=(mark['x'],mark['y'],z):raise ValueError('Point-mask position mismatch')
            source=plane(z);expected_source=plane_map[z]['sha256'] if z in plane_map else digest(inside(args.bundle,bundle['field_image']))
            if record.get('source_field_sha256')!=expected_source:raise ValueError('Point-mask source field mismatch')
            mask_path=inside(args.point_proposals,variant['mask'])
            if digest(mask_path)!=variant.get('mask_sha256'):raise ValueError('Selected point-mask hash mismatch')
            with Image.open(mask_path) as image:mask=image.convert('L')
            if mask.size!=(size,size):raise ValueError('Point-mask dimensions mismatch')
            mask=mask.point(lambda x:255 if x else 0)
            item['geometry']={'kind':'model_mask_reviewer_selected','z':z,'source_mask_sha256':digest(mask_path),
                              'proposal_manifest_sha256':digest(args.point_proposals/'proposals.json'),
                              'choice_review_sha256':mask_choice_hash,'variant':variant['name'],
                              'candidate_box_prompt':variant.get('candidate_box'),
                              'positive_point':variant.get('positive_point'),'negative_points':variant.get('negative_points'),
                              'negative_mark_ids':variant.get('negative_mark_ids'),'inference_bbox_xyxy':variant.get('inference_bbox_xyxy'),
                              'mask_reviewer_id':mask_reviewer,'mask_reviewer_role':mask_role,'mask_review_note':mask_note}
        elif candidate is not None and candidate.get('mask'):
            z=candidate.get('plane_z',bundle['z']);mask_path=inside(args.bundle,candidate['mask']);mask=Image.open(mask_path).convert('L')
            if mask.size!=(size,size):raise ValueError('Model mask dimensions mismatch')
            mask=mask.point(lambda x:255 if x else 0)
            item['geometry']={'kind':'model_mask_unverified','z':z,'bundle_mask':candidate['mask'],
                              'source_mask_sha256':digest(mask_path)}
        else:mask=None
        if mask is not None:
            bounds=mask.getbbox()
            if bounds is None:raise ValueError('Empty mask')
            source=plane(z);left,top,right,bottom=bounds;pad=8
            box=(max(0,left-pad),max(0,top-pad),min(size,right+pad),min(size,bottom+pad))
            number=len(specimens)+1;image_name=f'specimen-{number:04d}.png';mask_name=f'specimen-{number:04d}-mask.png'
            source.crop(box).save(args.output/image_name);mask.crop(box).save(args.output/mask_name)
            source_hash=(plane_map[z]['sha256'] if z in plane_map
                         else digest(inside(args.bundle,bundle['field_image'])))
            item['crop']={'image':image_name,'mask':mask_name,'field_bbox_xyxy':list(box),'z':z,
                          'source_field_sha256':source_hash,
                          'image_sha256':digest(args.output/image_name),'mask_sha256':digest(args.output/mask_name)}
        elif mark is not None:
            # A point establishes location, not a specimen boundary. Preserve its
            # surrounding pixels without presenting them as an isolated instance.
            z=mark.get('z',bundle['z']);source=plane(z);x,y=mark['x'],mark['y'];radius=args.point_crop_radius
            box=(max(0,math.floor(x)-radius),max(0,math.floor(y)-radius),
                 min(size,math.floor(x)+radius+1),min(size,math.floor(y)+radius+1))
            image_name=f'specimen-{len(specimens)+1:04d}.png';source.crop(box).save(args.output/image_name)
            source_hash=(plane_map[z]['sha256'] if z in plane_map
                         else digest(inside(args.bundle,bundle['field_image'])))
            item['crop']={'kind':'manual_point_context','image':image_name,'mask':None,
                          'field_bbox_xyxy':list(box),'z':z,'point_xy_in_crop':[x-box[0],y-box[1]],
                          'source_field_sha256':source_hash,'image_sha256':digest(args.output/image_name),
                          'mask_sha256':None}
        specimens.append(item)

    for candidate in candidates:
        if candidate['id'] in reviews:add(candidate['id'],reviews[candidate['id']],candidate=candidate)
    for i,mark in enumerate(manual,1):add(f'manual-{i:04d}',mark,mark=mark)
    result={'format':'diatom-reviewed-specimens-v1','sample_id':sample,'reviewer_id':reviewer,'reviewer_role':role,
            'review_context_as_exported':context,
            'review_source_sha256':digest(args.review),'bundle_id':bundle['bundle_id'],
            'slide':bundle['slide'],'slide_size_bytes':bundle.get('slide_size_bytes'),'origin_xy':origin,'calibration':bundle['calibration'],
            'field_exhaustiveness':{'not_evaluated':'not_recorded','complete':'reviewer_reported_complete',
                                    'incomplete':'reviewer_reported_incomplete'}[coverage], 'adjudicated':False,
            'warning':'Retain all overlapping/alternative records; no deduplication or ground-truth validation has been performed.',
            'candidate_relationships':relation_records,'specimens':specimens}
    (args.output/'specimens.json').write_text(json.dumps(result,indent=2)+'\n')
    print(f'Exported {len(specimens)} reviewer records to {args.output}; none are adjudicated.')


if __name__=='__main__':main()
