"""Recompute prompt geometry, mask scores and named-target neighbor overlaps."""
import collections
import json
import math
from pathlib import Path

import cv2
import numpy as np
import torch
from PIL import Image
from ultralytics.models.sam import Predictor
from ultralytics.utils import LOGGER

from diatom_pilot.gunduz_expansion_asset_dataset import GunduzExpansionAssets
from diatom_pilot.gunduz_species_asset_dataset import GunduzSpeciesAssets
from diatom_pilot.ude_scaleup_dataset import sha256
from r117_source_decoder_evaluate import iou
from r117_source_decoder_train import prepare

R = Path(__file__).resolve().parents[1]
O = R / 'results/r117'
D = R / 'datasets/r115-gunduz'
W = Path('/tmp/mobile_sam.pt')


def main():
    cv2.setNumThreads(2)
    torch.set_num_threads(2)
    LOGGER.setLevel('ERROR')
    p = json.loads((O / 'protocol.json').read_text())
    training = json.loads((O / 'training.json').read_text())
    result = json.loads((O / 'results.json').read_text())
    assert p['mobile_sam_sha256'] == sha256(W)
    assert training['protocol_sha256'] == result['protocol_sha256'] == sha256(O / 'protocol.json')
    assert result['training_sha256'] == sha256(O / 'training.json')
    assert training['checkpoint_sha256'] == sha256(O / training['checkpoint'])
    for path, digest in p['inputs_sha256'].items():
        assert sha256(R / path) == digest
    train = GunduzSpeciesAssets('consumed_development')
    compare = GunduzExpansionAssets('consumed_development')
    assert [r['id'] for r in train.records] == p['train_ids'] and [r['id'] for r in compare.records] == p['comparison_ids']
    assert not {r['source_image_id'] for r in train.records} & {r['source_image_id'] for r in compare.records}
    assert training['samples'] == len(train) == 26 and training['epochs'] == 3 and training['updates'] == 78
    for i, (meta, geom) in enumerate(zip(train.records, training['training_geometry'])):
        x = train[i]
        canvas, label, point, reconstructed = prepare(x['image'], x['source_component_mask'])
        target = torch.nn.functional.interpolate(torch.from_numpy(label.astype('float32'))[None, None], size=(128, 128), mode='nearest')
        assert geom == {'id': meta['id'], 'source_image_id': meta['source_image_id'],
                        'source_mask_sha256': meta['mask_sha256'], 'target_pixels_128': int(target.sum()), **reconstructed}
        assert target.any() and (target == 0).any()
    predictor = Predictor(overrides={'model': str(W), 'task': 'segment', 'mode': 'predict', 'imgsz': 512,
                                     'device': 'cpu', 'retina_masks': True, 'verbose': False, 'save': False, 'conf': 0.})
    predictor.set_image(np.full((512, 512, 3), 128, dtype=np.uint8))
    original = predictor.model.mask_decoder.state_dict()
    updated = torch.load(O / training['checkpoint'], map_location='cpu', weights_only=True)
    assert set(original) == set(updated)
    changed = 0
    for key in original:
        assert original[key].shape == updated[key].shape and torch.isfinite(updated[key]).all()
        changed += not torch.equal(original[key], updated[key])
    assert changed > 0
    summary = {'cases': len(compare), 'original': {}, 'adapted': {}}
    neighborhood = []
    assert len(result['records']) == len(compare) == 25
    for i, (meta, row) in enumerate(zip(compare.records, result['records'])):
        x = compare[i]
        assert row['id'] == meta['id'] and row['source_image_id'] == meta['source_image_id']
        assert row['source_name'] == meta['source_name'] and row['source_crop_sha256'] == meta['image_sha256']
        assert row['source_mask_sha256'] == meta['mask_sha256']
        gray, reference = np.asarray(x['image']), x['source_component_mask']
        _, _, _, geom = prepare(x['image'], reference)
        assert row['geometry'] == geom and row['reference_area_px'] == int(reference.sum())
        assert sha256(O / row['comparison']) == row['comparison_sha256']
        full_path = D / 'masks' / (meta['source_image_id'] + '.png')
        assert sha256(full_path) == meta['source_binary_mask_sha256']
        full = np.asarray(Image.open(full_path).convert('L')) > 0
        x0, y0, x1, y1 = meta['crop_bounds_xyxy_exclusive']
        crop_foreground = full[y0:y1, x0:x1]
        assert crop_foreground.shape == reference.shape and np.all(crop_foreground[reference])
        other_foreground = crop_foreground & ~reference
        details = {}
        for mode in ('original', 'adapted'):
            q = row['outputs'][mode]
            path = O / q['mask']
            assert path.resolve() == (O / 'masks' / (meta['id'] + '-' + mode + '.png')).resolve()
            assert sha256(path) == q['sha256']
            raw = np.asarray(Image.open(path).convert('L'))
            assert raw.shape == reference.shape and set(np.unique(raw)).issubset({0, 255})
            mask = raw > 0
            assert int(mask.sum()) == q['area_px'] and iou(mask, reference) == q['reference_iou']
            assert math.isfinite(q['model_score_not_accuracy'])
            details[mode + '_other_foreground_pixels'] = int((mask & other_foreground).sum())
        neighborhood.append({'id': meta['id'], 'other_source_foreground_pixels': int(other_foreground.sum()), **details})
    for key in ('original', 'adapted'):
        vals = [x['outputs'][key]['reference_iou'] for x in result['records']]
        summary[key] = {'iou_ge_05': sum(v >= .5 for v in vals), 'iou_ge_075': sum(v >= .75 for v in vals),
                        'mean_iou': float(np.mean(vals)), 'median_iou': float(np.median(vals))}
    summary['adapted_higher_iou'] = sum(x['outputs']['adapted']['reference_iou'] > x['outputs']['original']['reference_iou'] + 1e-9 for x in result['records'])
    summary['adapted_lower_iou'] = sum(x['outputs']['adapted']['reference_iou'] < x['outputs']['original']['reference_iou'] - 1e-9 for x in result['records'])
    summary['adapted_equal_iou'] = sum(abs(x['outputs']['adapted']['reference_iou'] - x['outputs']['original']['reference_iou']) <= 1e-9 for x in result['records'])
    assert summary == result['summary']
    audit = {'format': 'r117-neighbor-foreground-audit-v1', 'results_sha256': sha256(O / 'results.json'),
             'cases': len(neighborhood),
             'cases_with_other_source_foreground': sum(x['other_source_foreground_pixels'] > 0 for x in neighborhood),
             'cases_with_at_least_100_other_foreground_pixels': sum(x['other_source_foreground_pixels'] >= 100 for x in neighborhood),
             'original_masks_touching_other_source_foreground': sum(x['original_other_foreground_pixels'] > 0 for x in neighborhood),
             'adapted_masks_touching_other_source_foreground': sum(x['adapted_other_foreground_pixels'] > 0 for x in neighborhood),
             'warning': 'Other source-binary foreground can be diatoms or fragments; missing annotations are unknown. Touching any pixel is not an instance merge or accuracy rate.', 'records': neighborhood}
    (O / 'neighbor-audit.json').write_text(json.dumps(audit, indent=2) + '\n')
    out = {'format': 'r117-source-decoder-verify-v1', 'protocol_sha256': sha256(O / 'protocol.json'),
           'training_sha256': sha256(O / 'training.json'), 'results_sha256': sha256(O / 'results.json'),
           'neighbor_audit_sha256': sha256(O / 'neighbor-audit.json'), 'decoder_tensors_changed': changed,
           'training_geometries': len(train), 'comparison_masks': 2 * len(compare), 'summary': summary,
           'checks': 'Recomputed clicks, source masks, binary output mask hashes, IoUs, summaries and other-source-foreground intersections; verified decoder differs from base. Training and inference were not rerun; biological truth, sample independence and Academy accuracy are not established.'}
    (O / 'verify.json').write_text(json.dumps(out, indent=2) + '\n')
    print(json.dumps({'decoder_tensors_changed': changed, 'summary': summary,
                      'neighbor_counts': {k: v for k, v in audit.items() if k.startswith('cases_') or k.endswith('_foreground')}}, indent=2))


if __name__ == '__main__':
    main()
