"""Convert matching provisional practice marks into a portable field review."""
import argparse
import json
import math
from pathlib import Path

from ingest_review import digest


def main():
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--practice',type=Path,required=True);p.add_argument('--bundle',type=Path,required=True)
    p.add_argument('--output',type=Path,required=True);a=p.parse_args()
    if a.output.exists():raise FileExistsError('Refusing to replace an existing review')
    source=json.loads(a.practice.read_text());b=json.loads((a.bundle/'bundle.json').read_text())
    if source.get('role')!='nonexpert' or source.get('status')!='provisional':raise ValueError('Expected provisional nonexpert practice marks')
    matches=[x for x in source['fields'] if x.get('slide')==b['slide'] and x.get('origin_xy')==b['origin_xy']]
    if len(matches)!=1:raise ValueError('Expected exactly one matching practice field')
    f=matches[0]
    def manifest(name):
        path=a.bundle/name
        if not path.exists():return None
        value=json.loads(path.read_text())
        if value.get('bundle_id')!=b['bundle_id']:raise ValueError(f'Manifest does not match bundle: {name}')
        return value
    focus=manifest('focus-planes.json');split=manifest('split-alternatives.json');stack=manifest('stack-proposals.json')
    classifier=manifest('classifier-suggestions.json');alternative=manifest('classifier-alternative-suggestions.json')
    tile=manifest('tile-proposals.json')
    valid_z={x['z'] for x in focus['planes']} if focus else {b['z']};marks=[]
    for m in f['marks']:
        x,y,z=m['x'],m['y'],m['z'];flags=m.get('flags',[]);kind=m['kind']
        if (any(not isinstance(v,(int,float)) or isinstance(v,bool) or not math.isfinite(v) or not 0<=v<b['size'] for v in (x,y))
            or type(z) is not int or z not in valid_z or not isinstance(flags,list) or any(not isinstance(v,str) for v in flags)
            or kind not in {'Possible diatom','Unsure'}):raise ValueError('Invalid practice mark')
        if m.get('slide_x')!=b['origin_xy'][0]+x or m.get('slide_y')!=b['origin_xy'][1]+y:raise ValueError('Practice slide coordinates disagree')
        marks.append({'x':x,'y':y,'z':z,'decision':'possible' if kind=='Possible diatom' else 'unsure',
                      'species':'','partial':'yes' if 'partial' in flags else 'unknown','overlap':'unknown',
                      'note':'Provisional practice mark; original flags: '+(', '.join(flags) if flags else 'none')})
    context={'reviewer_role':'nonexpert','reviewer_id':'','sample_id':'','field_coverage':'not_evaluated',
             'practice_source_sha256':digest(a.practice),'practice_source_field':f['field'],
             'practice_source_status':'provisional','practice_source_hint_exposure':'unknown',
             'practice_source_field_note':f.get('note','')}
    result={'format':'diatom-field-review-v1','bundle':b,'focus_planes':focus,'split_alternatives':split,
            'stack_proposals':stack,'tile_proposals':tile,'classifier_suggestions':classifier,'alternative_classifier_suggestions':alternative,
            'review':{'context':context,'candidates':{},'manual':marks}}
    a.output.parent.mkdir(parents=True,exist_ok=True)
    with a.output.open('x') as out:json.dump(result,out,indent=2);out.write('\n')
    print(f'Converted {len(marks)} provisional marks to {a.output}')


if __name__=='__main__':main()
