"""New-branch RF mask contracts. No upstream/old module is patched on disk."""
from __future__ import annotations

import torch
from torch.nn import functional as F


def mask_logits(outputs, indices=None):
    """FP32 projection, preserving arbitrary (not necessarily batch-sorted) indices."""
    value = outputs['pred_masks']
    if isinstance(value, torch.Tensor):
        return value.float() if indices is None else value[indices].float()
    spatial, query, bias = (value[k].float() for k in ('spatial_features', 'query_features', 'bias'))
    with torch.autocast(device_type=spatial.device.type, enabled=False):
        if indices is None:
            return torch.einsum('bchw,bqc->bqhw', spatial, query) + bias
        batch, chosen = indices
        if not len(batch):
            # All three factors remain connected, including the learned bias.
            zero = (spatial.sum() + query.sum() + bias.sum()) * 0
            return spatial.new_empty((0, *spatial.shape[-2:])) + zero
        result = spatial.new_zeros((len(batch), *spatial.shape[-2:]))
        for b in batch.unique(sorted=True):
            positions = torch.where(batch == b)[0]
            result[positions] = torch.einsum('chw,qc->qhw', spatial[b], query[b, chosen[positions]]) + bias
        return result


def dense_losses(logits, labels, valid, num_boxes):
    """B0: original nearest dense lattice, padding ignored; FP32 reductions."""
    with torch.autocast(device_type=logits.device.type, enabled=False):
        logits = logits.float()
        label = F.interpolate(labels[:, None].float(), size=logits.shape[-2:], mode='nearest')[:, 0]
        weight = F.interpolate(valid[:, None].float(), size=logits.shape[-2:], mode='nearest')[:, 0]
        return binary_losses(logits.flatten(1), label.flatten(1), weight.flatten(1), num_boxes)


def binary_losses(logits, labels, weight, normalizer):
    with torch.autocast(device_type=logits.device.type, enabled=False):
        logits, labels, weight = logits.float(), labels.float(), weight.float()
        ce = (F.binary_cross_entropy_with_logits(logits, labels, reduction='none') * weight).sum(1)
        ce = ce / weight.sum(1).clamp_min(1)
        probability, positive = logits.sigmoid() * weight, labels * weight
        dice = 1 - (2 * (probability * positive).sum(1) + 1) / ((probability + positive).sum(1) + 1)
        denominator = torch.as_tensor(normalizer, device=logits.device, dtype=torch.float32).clamp_min(1)
        return dict(loss_mask_ce=ce.sum() / denominator, loss_mask_dice=dice.sum() / denominator)


def safe_mask_lattice(logits, valid):
    """Mask-head cells outside valid cannot affect valid-point interpolation.

    Labels stay at full input resolution. This does NOT nearest-downsample the
    B1 target; the lattice mask only prevents interpolation of ignored logits.
    """
    active = F.interpolate(valid[:, None].float(), size=logits.shape[-2:], mode='nearest-exact')[:, 0]
    return logits.float() * active


def valid_coords(valid, count):
    """Uniform replacement sampling of valid full-resolution pixel CENTERS."""
    coordinates = []
    for item in valid:
        locations = torch.nonzero(item > 0, as_tuple=False)
        if not len(locations):
            raise ValueError('Empty valid supervision region')
        chosen = locations[torch.randint(len(locations), (count,), device=item.device)]
        h, w = item.shape
        coordinates.append(torch.stack(((chosen[:, 1].float() + .5) / w,
                                        (chosen[:, 0].float() + .5) / h), -1))
    return torch.stack(coordinates)


def sample(value, coords, mode='bilinear'):
    return F.grid_sample(value[:, None].float(), coords[:, None].float() * 2 - 1,
                         mode=mode, align_corners=False)[:, 0, 0]


def point_losses(logits, labels, valid, num_boxes, count=2048):
    """B1 only: 75% uncertainty + 25% uniform valid input pixel centers."""
    with torch.autocast(device_type=logits.device.type, enabled=False):
        logits = safe_mask_lattice(logits, valid)
        with torch.no_grad():
            candidates = valid_coords(valid, count * 3)
            uncertainty = -sample(logits.detach(), candidates).abs()
            chosen = uncertainty.topk(int(count * .75), dim=1).indices
            hard = candidates.gather(1, chosen[:, :, None].expand(-1, -1, 2))
            coords = torch.cat((hard, valid_coords(valid, count - hard.shape[1])), 1)
            # Soft interpolation matches align_corners=False center geometry;
            # no mask-head nearest quantization of the supervision.
            target = sample(labels, coords)
        prediction = sample(logits, coords)
        return binary_losses(prediction, target, torch.ones_like(target), num_boxes)


def mask_loss(self, outputs, targets, indices, num_boxes):
    batch, query = self._get_src_permutation_idx(indices)
    logits = mask_logits(outputs, (batch, query))
    if not len(batch):
        zero = logits.sum() * 0
        return dict(loss_mask_ce=zero, loss_mask_dice=zero)
    labels = torch.cat([t['masks'][j] for t, (_, j) in zip(targets, indices)])
    valid = torch.cat([t['pixel_valid'][None].expand(len(j), -1, -1)
                       for t, (_, j) in zip(targets, indices)])
    loss = point_losses if self.improvement_point_loss else dense_losses
    return loss(logits, labels, valid, num_boxes)


def mask_costs(self, outputs, targets):
    """Shared B0/B1 matcher: original global random points + valid ignore.

    Sampling distribution, count and costs are held fixed across B0/B1.
    Only FP32 accumulation and masking interpolation inputs are contract fixes.
    """
    value = outputs['pred_masks']
    if isinstance(value, torch.Tensor):
        b, q, h, w = value.shape
        device = value.device
    else:
        b, _, h, w = value['spatial_features'].shape
        q = value['query_features'].shape[1]
        device = value['spatial_features'].device
    total = sum(len(t['masks']) for t in targets)
    if total == 0:
        zero = mask_logits(outputs).sum() * 0
        return (torch.empty(b * q, 0, device=device) + zero,) * 2
    with torch.autocast(device_type=device.type, enabled=False):
        # Project once per image, not all 13 groups over the entire dense grid.
        coords = torch.rand(1, max(128, h * w // self.mask_point_sample_ratio), 2, device=device)
        validity = torch.stack([t['pixel_valid'].float() for t in targets])
        active = F.interpolate(validity[:, None], size=(h, w), mode='nearest-exact')
        if isinstance(value, torch.Tensor):
            pred = value.float() * active
            logits = sample(pred.flatten(0, 1), coords.expand(b * q, -1, -1))
        else:
            features = value['spatial_features'].float() * active
            points = F.grid_sample(features, coords[:, None].expand(b, -1, -1, -1) * 2 - 1,
                                   align_corners=False)[:, :, 0]
            # Bias must be masked too, including bilinear transitions to padding.
            activity = sample(active[:, 0], coords.expand(b, -1, -1))
            logits = (torch.einsum('bcp,bqc->bqp', points, value['query_features'].float())
                      + value['bias'].float() * activity[:, None]).flatten(0, 1)
        masks = torch.cat([t['masks'] for t in targets]).float()
        valid = torch.cat([t['pixel_valid'][None].expand(len(t['masks']), -1, -1) for t in targets]).float()
        points = coords.expand(total, -1, -1)
        label, weight = sample(masks, points, 'nearest'), sample(valid, points, 'nearest')
        pos, neg = label * weight, (1 - label) * weight
        ce = (F.softplus(-logits) @ pos.T + F.softplus(logits) @ neg.T) / weight.sum(1).clamp_min(1)[None]
        probability = logits.sigmoid()
        dice = 1 - (2 * (probability @ pos.T) + 1) / (probability @ weight.T + pos.sum(1)[None] + 1)
        return ce, dice


def native_logits(logits, transform):
    """Raw float logits → full letterbox → native → sigmoid → threshold ONCE."""
    width, height = transform['output_size']
    left, top = transform['padding_left_top']
    nw, nh = transform['scaled_size']
    native_w, native_h = transform['native_size']
    with torch.autocast(device_type=logits.device.type, enabled=False):
        full = F.interpolate(logits.float()[None, None], size=(height, width), mode='bilinear', align_corners=False)
        return F.interpolate(full[:, :, top:top+nh, left:left+nw], size=(native_h, native_w),
                             mode='bilinear', align_corners=False)[0, 0]


def highest_class_query(outputs):
    """No target/reference/topology argument exists at inference selection."""
    probabilities = outputs['pred_logits'].float().sigmoid()[0]
    return int(probabilities.max(1).values.argmax()), float(probabilities.max())
