"""Compare the preview's preprocessing with an explicitly supplied author script.

The provided Python file is executed. Use only the inspected, trusted upstream
source and check its pinned SHA-256 before running this script.
"""
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():
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument('--author-script',type=Path,required=True)
    args=p.parse_args()
    if hashlib.sha256(args.author_script.read_bytes()).hexdigest()!=EXPECTED:
        raise ValueError('Author script hash differs from the inspected upstream version')
    spec=importlib.util.spec_from_file_location('diamorph_author_preprocess',args.author_script)
    author=importlib.util.module_from_spec(spec);spec.loader.exec_module(author)
    directory=ROOT/'results/pilot/field-01';bundle=json.loads((directory/'bundle.json').read_text());scale=bundle['calibration']
    records=[]
    with tempfile.TemporaryDirectory(prefix='diatom-parity-') as tmp:
        for candidate in bundle['candidates']:
            source=directory/candidate['crop'];expected=Path(tmp)/'author.png'
            author.pad_crop_image(str(source),expected,scale['x_um_per_pixel'],512,.1)
            reference=cv2.imread(str(expected),cv2.IMREAD_GRAYSCALE)
            ours=preprocess(cv2.imread(str(source)),scale['x_um_per_pixel'],scale['y_um_per_pixel'])
            gray=cv2.cvtColor(ours,cv2.COLOR_BGR2GRAY)
            difference=np.abs(reference.astype(np.int16)-gray.astype(np.int16))
            records.append({'candidate_id':candidate['id'],'different_pixels':int((difference>0).sum()),
                            'maximum_intensity_difference':int(difference.max())})
    output=ROOT/'results/pilot/diamorph-robustness/parity.json'
    output.parent.mkdir(parents=True,exist_ok=True)
    output.write_text(json.dumps({'author_script_sha256':EXPECTED,'author_scalar_um_per_pixel':scale['x_um_per_pixel'],
        'local_x_um_per_pixel':scale['x_um_per_pixel'],'local_y_um_per_pixel':scale['y_um_per_pixel'],
        'records':records},indent=2)+'\n')
    print(json.dumps(records,indent=2))


if __name__=='__main__':main()
