"""Freeze an additional, training-location-only UDE breadth/depth selection."""
import collections
import csv
import hashlib
import json
from pathlib import Path

from diatom_pilot.ude_development_archive import sha256, source_name_flags

R = Path(__file__).resolve().parents[1]
O = R / 'results/r112/species-breadth-extension'
M = Path('/tmp/ude-metadata.csv')
L = R / 'results/r112/ude-sampling-metadata/exposure-ledger.csv'
E = R / 'results/r112/ude-sampling-metadata/exposure-report.json'
B = R / 'results/r112/species-breadth/selection.json'
P = R / 'results/r112/species-scaleup/location-partitions.json'


def main():
    O.mkdir(parents=True, exist_ok=True)
    output = O / 'selection.json'
    if output.exists():
        raise FileExistsError(output)
    exposure, prior, partitions = (json.loads(p.read_text()) for p in (E, B, P))
    assert sha256(M) == exposure['metadata_sha256'] and sha256(L) == exposure['ledger_sha256']
    groups = partitions['group_partition']
    selected_ids = {r['annotation_id'] for r in prior['records']}
    component_counts = collections.Counter()
    slide_counts = collections.Counter()
    totals = collections.Counter()
    for r in prior['records']:
        if groups.get(r['site_component']) == 'training':
            name = r['source_species']
            totals[name] += 1
            component_counts[name, r['site_component']] += 1
            slide_counts[name, r['source_slide']] += 1
    before = dict(totals)
    ledger = {}
    with L.open(newline='', encoding='utf-8') as f:
        for r in csv.DictReader(f):
            if (r['exposure_status'] == 'prior_development'
                    and groups.get(r['site_component']) == 'training'
                    and r['species'] in prior['per_name']
                    and not source_name_flags(r['genus'], r['species'])
                    and r['annotation_id'] not in selected_ids):
                ledger[r['annotation_id']] = r
    pool = collections.defaultdict(list)
    with M.open(newline='', encoding='utf-8-sig') as f:
        for m in csv.DictReader(f):
            r = ledger.get(m['annotation_id'])
            if not r:
                continue
            assert m['species'] == r['species'] and m['genus'] == r['genus']
            w = int(m['bbox_x1']) - int(m['bbox_x0']) + 1
            h = int(m['bbox_y1']) - int(m['bbox_y0']) + 1
            if min(w, h) < 15 or max(w, h) > 4096 or w * h > 16_000_000:
                continue
            pool[r['species']].append({
                'annotation_id': r['annotation_id'], 'source_species': r['species'],
                'source_genus': r['genus'], 'source_site_component': r['site_component'],
                'source_slide_group': r['image_filename'], 'source_annotation_shape': r['annotation_shape'],
                'source_bbox_global': [int(m[k]) for k in ('bbox_x0', 'bbox_y0', 'bbox_x1', 'bbox_y1')],
                'source_annotation_points_global': json.loads(m['points']),
                'source_annotator': m['annotator'], 'source_subspecies': m['subspecies']})
    records = []
    for name in sorted(prior['per_name']):
        candidates = pool[name]
        while totals[name] < 24:
            eligible = [r for r in candidates if component_counts[name, r['source_site_component']] < 4
                        and slide_counts[name, r['source_slide_group']] < 2]
            if not eligible:
                break
            def key(r):
                digest = hashlib.sha256(('r112-depth-v1:' + r['annotation_id']).encode()).hexdigest()
                return (component_counts[name, r['source_site_component']],
                        slide_counts[name, r['source_slide_group']], digest)
            r = min(eligible, key=key)
            candidates.remove(r)
            component_counts[name, r['source_site_component']] += 1
            slide_counts[name, r['source_slide_group']] += 1
            totals[name] += 1
            records.append(r)
    assert len({r['annotation_id'] for r in records}) == len(records)
    assert all(groups[r['source_site_component']] == 'training' for r in records)
    assert all(n <= 4 for n in component_counts.values()) and all(n <= 2 for n in slide_counts.values())
    result = {'format': 'r112-breadth-depth-extension-selection-v1',
              'selection': 'Metadata-only: extend each of the 137 previous breadth names to at most 24 crops, using only prior-development training location components; include previous eligible crops in component (4) and slide (2) caps, choose least represented components/slides first and hash-break ties.',
              'warning': 'Source names and masks are unverified, crops may contain other organisms, location proxies do not establish independent specimens, and prior comparisons exposed some other breadth crops.',
              'inputs_sha256': {str(p.relative_to(R)): sha256(p) for p in (L, E, B, P)},
              'metadata_sha256': sha256(M), 'script_sha256': sha256(Path(__file__)),
              'before_by_name': before, 'after_by_name': dict(totals), 'records': records}
    output.write_text(json.dumps(result, indent=2) + '\n')
    print('selected', len(records), 'additional crops for', len({r['source_species'] for r in records}), 'names')
    print('names reaching 24:', sum(totals[n] >= 24 for n in prior['per_name']))


if __name__ == '__main__':
    main()
