"""Train a point-prompted decoder on consumed Gündüz component candidates."""
import ctypes
import json
import os
import random
import signal
import time
from pathlib import Path

import cv2
import numpy as np
import torch
import torch.nn.functional as F
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

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


def prepare(image, mask):
    """Reference-derived interior click and median-padded 512px source crop."""
    gray = np.asarray(image)
    h, w = gray.shape
    assert mask.shape == (h, w) and mask.any()
    distance = cv2.distanceTransform(mask.astype('uint8'), cv2.DIST_L2, 5)
    y, x = np.unravel_index(int(np.argmax(distance)), distance.shape)
    assert mask[y, x]
    scale = min(1., 512 / max(w, h))
    iw, ih = max(1, round(w * scale)), max(1, round(h * scale))
    ox, oy = (512 - iw) // 2, (512 - ih) // 2
    source = gray if (iw, ih) == (w, h) else cv2.resize(gray, (iw, ih), interpolation=cv2.INTER_AREA)
    label = cv2.resize(mask.astype('uint8'), (iw, ih), interpolation=cv2.INTER_NEAREST)
    canvas = np.full((512, 512), int(np.median(gray)), np.uint8)
    full_mask = np.zeros((512, 512), np.uint8)
    canvas[oy:oy+ih, ox:ox+iw] = source
    full_mask[oy:oy+ih, ox:ox+iw] = label
    point = [ox + float(x) * iw / w, oy + float(y) * ih / h]
    return canvas, full_mask, point, {'source_point_xy': [int(x), int(y)],
                                     'source_size_xy': [w, h], 'resized_size_xy': [iw, ih],
                                     'padding_xy': [ox, oy], 'inference_point_xy': point}


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')
    cv2.setNumThreads(2)
    torch.set_num_threads(2)
    torch.manual_seed(1172026)
    rng = random.Random(1172026)
    LOGGER.setLevel('ERROR')
    O.mkdir(exist_ok=True)
    assert not (O / 'protocol.json').exists()
    train = GunduzSpeciesAssets('consumed_development')
    compare = GunduzExpansionAssets('consumed_development')
    assert len(train) == 26 and len(compare) == 25
    train_images = {r['source_image_id'] for r in train.records}
    compare_images = {r['source_image_id'] for r in compare.records}
    assert not train_images & compare_images
    inputs = ['results/r112/gunduz-species-assets/assets.json', 'results/r112/gunduz-species-assets/verify.json',
              'results/r112/gunduz-expansion-assets/assets.json', 'results/r112/gunduz-expansion-assets/verify.json',
              'diatom_pilot/gunduz_species_asset_dataset.py', 'diatom_pilot/gunduz_expansion_asset_dataset.py',
              'research/r117_source_decoder_train.py', 'research/r117_source_decoder_evaluate.py']
    protocol = {'format': 'r117-source-decoder-protocol-v1', 'inputs_sha256': {f: sha256(R / f) for f in inputs},
                'mobile_sam_sha256': sha256(W), 'seed': 1172026,
                'train_ids': [r['id'] for r in train.records], 'comparison_ids': [r['id'] for r in compare.records],
                'selection': 'All 26 previously consumed source components train the decoder. All 25 previously consumed expansion components are a separate-image development comparison, not a final holdout; source image IDs do not overlap and a coarse similarity screen was already applied.',
                'preprocess': 'Native grayscale crop, downsize to fit a 512×512 median-padded canvas. Positive click is the maximum-distance interior point from the source component mask. This is privileged reference-derived input, not automatic target acquisition.',
                'training': 'Initialize the public MobileSAM checkpoint; freeze image and prompt encoders, cache 26 embeddings, train mask decoder only for 3 epochs using AdamW learning rate 1e-5, zero weight decay, binary cross entropy plus soft Dice on 128×128 nearest-resampled target mask. Zero outside the target means not this queried instance, not semantic absence of diatoms.',
                'comparison': 'Fixed original and adapted decoder on all 25 comparison components, identical reference-derived click and preprocessing; compute component IoU per object and counts at 0.5 and 0.75. Save all masks and predictions; no model selection based on comparison.',
                'warning': 'Both pools were previously inspected and used for synthetic development. Source labels and structurally inferred component associations are not independently adjudicated; near-duplicate screen cannot establish sample, site or pretraining independence. Scale and optics unknown. Oracle positive clicks and crops, plus unlabelled neighboring organisms, make this a development proxy, not automatic Academy or true overlap performance. Dataset CC BY-NC-SA 4.0.'}
    (O / 'protocol.json').write_text(json.dumps(protocol, indent=2) + '\n')
    start = time.monotonic()
    predictor = Predictor(overrides={'model': str(W), 'task': 'segment', 'mode': 'predict', 'imgsz': 512,
                                     'device': 'cpu', 'retina_masks': True, 'verbose': False, 'save': False, 'conf': 0.})
    samples, geometry = [], []
    for i, meta in enumerate(train.records):
        item = train[i]
        canvas, mask, point, geom = prepare(item['image'], item['source_component_mask'])
        predictor.set_image(cv2.cvtColor(canvas, cv2.COLOR_GRAY2BGR))
        features = predictor.features.clone().detach()
        mask_tensor = torch.from_numpy(mask.astype('float32'))[None, None]
        target = F.interpolate(mask_tensor, size=(128, 128), mode='nearest')
        assert target.any() and (target == 0).any()
        samples.append({'features': features, 'target': target,
                        'points': torch.tensor([[point]], dtype=torch.float32),
                        'labels': torch.tensor([[1]], dtype=torch.int64)})
        geometry.append({'id': meta['id'], 'source_image_id': meta['source_image_id'],
                         'source_mask_sha256': meta['mask_sha256'], 'target_pixels_128': int(target.sum()), **geom})
    model = predictor.model
    for param in model.parameters():
        param.requires_grad_(False)
    for param in model.mask_decoder.parameters():
        param.requires_grad_(True)
    model.eval()
    model.mask_decoder.train()
    optimizer = torch.optim.AdamW(model.mask_decoder.parameters(), lr=1e-5, weight_decay=0.)
    epoch_losses = []
    for epoch in range(3):
        order = list(range(len(samples)))
        rng.shuffle(order)
        losses = []
        for i in order:
            sample = samples[i]
            with torch.no_grad():
                sparse, dense = model.prompt_encoder(points=(sample['points'], sample['labels']), boxes=None, masks=None)
                pe = model.prompt_encoder.get_dense_pe()
            logits, _ = model.mask_decoder(image_embeddings=sample['features'], image_pe=pe,
                                           sparse_prompt_embeddings=sparse, dense_prompt_embeddings=dense,
                                           multimask_output=False)
            target = sample['target']
            assert logits.shape == target.shape
            bce = F.binary_cross_entropy_with_logits(logits, target)
            probability = logits.sigmoid()
            dice = 1 - (2 * (probability * target).sum() + 1) / (probability.sum() + target.sum() + 1)
            loss = bce + dice
            assert torch.isfinite(loss)
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            losses.append(float(loss.detach()))
        epoch_losses.append(float(np.mean(losses)))
        print('epoch', epoch+1, '/ 3; mean loss', round(epoch_losses[-1], 5), flush=True)
    checkpoint = O / 'decoder.pt'
    torch.save(model.mask_decoder.state_dict(), checkpoint)
    (O / 'training.json').write_text(json.dumps({'format': 'r117-source-decoder-training-v1',
                                                'protocol_sha256': sha256(O / 'protocol.json'),
                                                'checkpoint': checkpoint.name, 'checkpoint_sha256': sha256(checkpoint),
                                                'samples': len(samples), 'epochs': 3, 'updates': 3*len(samples),
                                                'mean_epoch_losses': epoch_losses, 'training_geometry': geometry,
                                                'elapsed_seconds': round(time.monotonic()-start, 2),
                                                'warning': protocol['warning']}, indent=2) + '\n')


if __name__ == '__main__':
    main()
