"""Compare local and author preprocessing on the fixed public UDE crop set.

This executes the supplied source file after verifying its recorded hash.
"""
import argparse
import hashlib
import importlib.util
import json
import tempfile
from pathlib import Path

import cv2
import numpy as np
from diamorph_preview import preprocess

EXPECTED='a8e26937eddbf006a255dcc8f2f0e72b9d74a5708156c815d28283758a952a49'
ROOT=Path(__file__).resolve().parent.parent


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--author-script',type=Path,required=True)
    args=parser.parse_args()
    if hashlib.sha256(args.author_script.read_bytes()).hexdigest()!=EXPECTED:raise ValueError('Uninspected author script')
    spec=importlib.util.spec_from_file_location('diamorph_author',args.author_script)
    author=importlib.util.module_from_spec(spec);spec.loader.exec_module(author)
    root=ROOT/'results/pilot/diamorph-ude-diagnostic'
    diagnostic=json.loads((root/'diagnostic.json').read_text());records=[]
    with tempfile.TemporaryDirectory(prefix='diatom-ude-parity-') as tmp:
        for row in diagnostic['records']:
            source=ROOT/row['image'];out=Path(tmp)/'author.png'
            author.pad_crop_image(str(source),out,.09,512,.1)
            reference=cv2.imread(str(out),cv2.IMREAD_GRAYSCALE)
            predicted=cv2.cvtColor(preprocess(cv2.imread(str(source)),.09,.09),cv2.COLOR_BGR2GRAY)
            diff=np.abs(reference.astype('int16')-predicted.astype('int16'))
            records.append({'annotation_id':row['annotation_id'],'different_pixels':int((diff>0).sum()),
                            'max_difference':int(diff.max())})
    (root/'parity.json').write_text(json.dumps({'author_script_sha256':EXPECTED,'records':records},indent=2)+'\n')
    print('Crops compared:',len(records),'with differences:',sum(x['different_pixels']>0 for x in records),flush=True)


if __name__=='__main__':main()
