"""Freeze and retrieve remaining already-audited Gündüz development images."""
import concurrent.futures
import ctypes
import json
import os
import signal
from pathlib import Path

from diatom_pilot.ude_scaleup_dataset import sha256
from r46_fetch_cases import get

R = Path(__file__).resolve().parents[1]
D = R / 'datasets/r112-gunduz-expansion'
O = R / 'results/r112/gunduz-expansion'


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')
    O.mkdir(exist_ok=True)
    (D / 'images').mkdir(parents=True, exist_ok=True)
    audit_path = R / 'results/r115/annotation-audit.json'
    audit = json.loads(audit_path.read_text())
    existing = {x['id'] for x in audit['selected']}
    selected = [x['id'] for x in audit['records'] if x['status'] == 'structural_match' and x['id'] not in existing]
    assert len(selected) == 22 and len(set(selected)) == 22
    inputs = ['results/r115/annotation-audit.json', 'results/r115/annotation-verify.json',
              'results/r115/protocol.json', 'results/r46/inventory.json',
              'research/r46_fetch_cases.py', 'research/r112_gunduz_expansion_fetch.py']
    protocol_path = O / 'protocol.json'
    protocol = {'format': 'r112-gunduz-expansion-protocol-v1',
                'inputs_sha256': {f: sha256(R / f) for f in inputs}, 'image_ids': selected,
                'selection': 'All 22 previously annotation-audited R115 preselection IDs that passed its structural matching rule but were not among the first 24 image selections. Images are now explicitly designated development, not an independent holdout; no other source image IDs are requested.',
                'license': 'Gündüz Diatom Dataset CC BY-NC-SA 4.0; noncommercial use, attribution and share-alike requirements apply.',
                'limits': 'Annotation masks and metadata were previously accessed; image sample independence, taxonomic reconciliation, physical scale, component correctness and duplication against other sources remain unresolved. No crops should be promoted to labels based on structure alone.'}
    if protocol_path.exists():
        if json.loads(protocol_path.read_text()) != protocol:
            raise ValueError('Frozen protocol differs')
    else:
        protocol_path.write_text(json.dumps(protocol, indent=2) + '\n')
    inventory = json.loads((R / 'results/r46/inventory.json').read_text())
    sizes = {x['name']: x['bytes'] for x in inventory['files']}
    output = O / 'image-manifest.json'
    if output.exists():
        raise FileExistsError(output)
    def fetch(ident):
        name = f'images/{ident}.png'
        data = get(name, sizes[name])
        path = D / 'images' / f'{ident}.png'
        if path.exists():
            if path.read_bytes() != data:
                raise ValueError('Existing file differs: ' + ident)
        else:
            temp = path.with_suffix('.png.tmp')
            temp.write_bytes(data)
            temp.replace(path)
        return {'id': ident, 'path': str(path.relative_to(R)), 'bytes': len(data), 'sha256': sha256(path)}
    with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
        rows = list(pool.map(fetch, selected))
    result = {'format': 'r112-gunduz-expansion-images-v1', 'protocol_sha256': sha256(protocol_path),
              'records': rows, 'warning': protocol['limits']}
    output.write_text(json.dumps(result, indent=2) + '\n')
    print('retrieved', len(rows), 'previously annotation-audited images', flush=True)


if __name__ == '__main__':
    main()
