"""Extract the frozen extra UDE crops, without inferring masks or labels."""
import ctypes
import json
import os
import signal
from pathlib import Path

from diatom_pilot.ude_development_archive import UDEDevelopmentArchive, sha256

R = Path(__file__).resolve().parents[1]
O = R / 'results/r112/species-breadth-extension'


def main():
    parent = os.getppid()
    assert ctypes.CDLL(None, use_errno=True).prctl(1, signal.SIGTERM) == 0
    if parent != os.getppid():
        raise RuntimeError('Parent exited')
    selection_path = O / 'selection.json'
    selection = json.loads(selection_path.read_text())
    assert not (O / 'assets.json').exists()
    for path, digest in selection['inputs_sha256'].items():
        assert sha256(R / path) == digest
    assert sha256(Path('/tmp/ude-metadata.csv')) == selection['metadata_sha256']
    assert sha256(R / 'research/r112_breadth_depth_extension_select.py') == selection['script_sha256']
    (O / 'images').mkdir(exist_ok=True)
    rows = []
    with UDEDevelopmentArchive() as archive:
        for r in selection['records']:
            value = archive.read(r['annotation_id'], require_plain_species=True)
            assert value['source_name'] == r['source_species']
            assert value['source_genus'] == r['source_genus']
            assert value['source_slide'] == r['source_slide_group']
            assert value['site_component'] == r['source_site_component']
            assert value['source_annotation_shape'] == r['source_annotation_shape']
            target = O / 'images' / (r['annotation_id'] + '.png')
            temp = target.with_suffix('.png.tmp')
            value['image'].save(temp, format='PNG')
            temp.replace(target)
            rows.append({**r, 'source_crop': str(target.relative_to(O)),
                         'source_sha256': sha256(target),
                         'archive_member_sha256': value['archive_member_sha256'],
                         'archive_member_crc32': value['archive_member_crc32'],
                         'source_dimensions_px': list(value['image'].size),
                         'source_scale_um_px': value['source_um_per_pixel_xy'],
                         'taxonomic_status': 'UDE source name; not independently reconciled',
                         'mask_status': 'no verified instance mask',
                         'source_sample_independence': 'unknown',
                         'background_status': 'unknown; crop may contain other organisms'})
            if len(rows) % 200 == 0:
                print('extracted', len(rows), '/', len(selection['records']), flush=True)
    result = {'format': 'r112-breadth-depth-extension-assets-v1',
              'selection_sha256': sha256(selection_path),
              'archive_verification_sha256': sha256(R / 'results/r112/ude-sampling-metadata/archive-verification.json'),
              'script_sha256': sha256(Path(__file__)),
              'source': 'UDE Diatoms in the Wild 2024, CC0; source names not independently reconciled.',
              'warning': selection['warning'], 'records': rows}
    (O / 'assets.json').write_text(json.dumps(result, indent=2) + '\n')
    print('complete', len(rows), 'additional grayscale source crops', flush=True)


if __name__ == '__main__':
    main()
