"""Convert provisional development points into a matching field-review export.

The source remains provisional; imported points are suggestions for further review,
not expert ground truth or accepted segmentation masks.
"""
import argparse
import hashlib
import json
import math
from pathlib import Path
from ingest_review import digest, inside


def convert(source_path, bundle_dir):
    source=json.loads(source_path.read_text());context=source.get('context',{});state=source.get('state',{})
    if (source.get('format')!='diatom-provisional-development-annotations-v1' or source.get('annotation_status')!='provisional'
        or context.get('purpose')!='development' or context.get('source_kind')!='unscored_scan'
        or context.get('split') not in {'practice','train','validation'}):raise ValueError('Expected provisional development annotations')
    bundle=json.loads((bundle_dir/'bundle.json').read_text())
    unsigned={k:v for k,v in bundle.items() if k!='bundle_id'}
    if bundle.get('bundle_id')!=hashlib.sha256(json.dumps(unsigned,sort_keys=True).encode()).hexdigest():raise ValueError('Invalid bundle identity')
    for a,b in [('slide','slide'),('slide_size_bytes','slide_size_bytes'),('origin_xy','origin_xy'),('size','size'),('model_z','z')]:
        if context.get(a)!=bundle.get(b):raise ValueError('Scan field does not match bundle')
    if digest(inside(bundle_dir,bundle['field_image']))!=context.get('field_image_sha256'):raise ValueError('Field image does not match')
    focus=json.loads((bundle_dir/'focus-planes.json').read_text())
    if focus.get('format')!='diatom-focus-planes-v1' or focus.get('bundle_id')!=bundle['bundle_id']:raise ValueError('Invalid focal planes')
    planes={p['z']:p for p in focus['planes']}; reference_planes=context.get('planes')
    if not isinstance(reference_planes,list) or len(reference_planes)!=len(planes):raise ValueError('Focal planes do not match')
    seen=set()
    for p in reference_planes:
        z=p.get('z'); actual=planes.get(z)
        if z in seen or actual is None or digest(inside(bundle_dir,actual['image']))!=actual.get('sha256') or p.get('sha256')!=actual['sha256']:raise ValueError('Focal plane image does not match')
        seen.add(z)
    if not isinstance(state,dict) or not isinstance(state.get('references'),list) or not isinstance(state.get('reviewer_id'),str) or not state['reviewer_id'].strip() or state.get('reviewer_role') not in {'unknown','nonexpert','expert'}:raise ValueError('Invalid reviewer or points')
    manual=[];ids=set()
    for item in state['references']:
        xy=item.get('field_xy');z=item.get('z');ident=item.get('id')
        if (not isinstance(ident,str) or not ident or ident in ids or not isinstance(xy,list) or len(xy)!=2
            or any(type(v) not in (int,float) or not math.isfinite(v) or not 0<=v<bundle['size'] for v in xy) or z not in planes
            or item.get('partial') not in {'unknown','yes','no'} or not all(isinstance(item.get(k),str) for k in ('genus','species','overlap_group'))):raise ValueError('Invalid provisional point')
        ids.add(ident);genus=item['genus'].strip();species=item['species'].strip();group=item['overlap_group'].strip()
        manual.append({'x':xy[0],'y':xy[1],'z':z,'decision':'possible','species':species or genus,
            'taxon_rank':'species' if species else 'genus' if genus else 'unknown','identification_certainty':'tentative' if species or genus else 'unknown',
            'partial':item['partial'],'overlap':'yes' if group else 'unknown','overlap_group':group,
            'note':'Provisional point '+ident+' from source '+digest(source_path)})
    def optional(name):
        path=bundle_dir/name
        return json.loads(path.read_text()) if path.exists() else None
    return {'format':'diatom-field-review-v1','bundle':bundle,'focus_planes':focus,
            'split_alternatives':optional('split-alternatives.json'),'stack_proposals':optional('stack-proposals.json'),
            'tile_proposals':optional('tile-proposals.json'),
            'review':{'context':{'reviewer_id':state['reviewer_id'].strip(),'reviewer_role':state['reviewer_role'],
                'sample_id':context.get('sample_id',''),'field_coverage':'not_evaluated',
                'development_split':context['split'],'provisional_source_sha256':digest(source_path)},'candidates':{},'manual':manual}}


def main():
    parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--annotations',required=True,type=Path);parser.add_argument('--bundle',required=True,type=Path);parser.add_argument('--output',required=True,type=Path);a=parser.parse_args()
    result=convert(a.annotations,a.bundle)
    with a.output.open('x') as out:json.dump(result,out,indent=2);out.write('\n')
    print('Created provisional field review; open it in the matching review page for further work.')


if __name__=='__main__':main()
