"""Compare atlas-control preprocessing with inspected upstream Python 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():
    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)
    rows=json.loads(Path('/tmp/diatom-diatlas-controls/selection.json').read_text())['rows'];records=[]
    with tempfile.TemporaryDirectory(prefix='diatom-atlas-parity-') as tmp:
        for row in rows:
            path=Path(row['local_file']);scale=row['scale_um_per_pixel'];output=Path(tmp)/'author.png'
            if hashlib.sha256(path.read_bytes()).hexdigest()!=row['sha256']:raise ValueError('Source control image changed')
            author.pad_crop_image(str(path),output,scale,512,.1)
            reference=cv2.imread(str(output),cv2.IMREAD_GRAYSCALE)
            ours=cv2.cvtColor(preprocess(cv2.imread(str(path)),scale,scale),cv2.COLOR_BGR2GRAY)
            diff=np.abs(reference.astype('int16')-ours.astype('int16'))
            records.append({'code':row['species_code'],'different_pixels':int((diff>0).sum()),'max_difference':int(diff.max())})
    out=ROOT/'results/pilot/diamorph-atlas-controls/parity.json'
    out.write_text(json.dumps({'author_script_sha256':EXPECTED,'records':records},indent=2)+'\n')
    print('Controls compared:',len(records),'with pixel differences:',sum(r['different_pixels']>0 for r in records))


if __name__=='__main__':main()
