"""Four-channel training data with synchronized letterboxing and box transforms."""

from __future__ import annotations

from dataclasses import dataclass

import numpy as np
import torch
from torch.nn import functional as F
from torch.utils.data import Dataset

from pallet.data import apply_normalization, load_frame
from pallet.annotation import is_resolved, reference_eligible


@dataclass(frozen=True)
class SampleMeta:
    frame_id: str
    original_size: tuple[int, int]
    scale: float
    padding: tuple[int, int]


def letterbox_float(image: np.ndarray, size: int = 640) -> tuple[torch.Tensor, float, tuple[int, int]]:
    """Resize without distorting geometry; preserve zero as missing-signal padding."""
    if image.ndim != 3 or image.shape[2] != 4:
        raise ValueError("expected HxWx4 depth/intensity/mask array")
    h, w = image.shape[:2]
    if h <= 0 or w <= 0:
        raise ValueError("image has empty dimension")
    scale = min(size / w, size / h)
    rw, rh = max(1, round(w * scale)), max(1, round(h * scale))
    tensor = torch.from_numpy(np.ascontiguousarray(image.transpose(2, 0, 1))).float()[None]
    support = F.interpolate(tensor[:, 2:], size=(rh, rw), mode="bilinear", align_corners=False)
    values = F.interpolate(tensor[:, :2] * tensor[:, 2:], size=(rh, rw),
                           mode="bilinear", align_corners=False) / support.clamp_min(1e-6)
    valid = F.interpolate(tensor[:, 2:], size=(rh, rw), mode="nearest") * (support > 0)
    resized = torch.cat((values * valid, valid), dim=1)
    left, top = (size - rw) // 2, (size - rh) // 2
    padded = F.pad(resized, (left, size - rw - left, top, size - rh - top), value=0)
    return padded[0], scale, (left, top)


class PalletDataset(Dataset):
    def __init__(self, records, annotation_set, normalization, *, size=640, require_review=True,
                 augmentation=False, mosaic=False, spatial_augmentation=False,
                 manual_training_ids=frozenset(), manual_validation_ids=frozenset(),
                 manual_role=None, manual_annotation_scope=None):
        by_id = annotation_set.frames
        manual_training_ids = frozenset(manual_training_ids)
        manual_validation_ids = frozenset(manual_validation_ids)
        if manual_training_ids & manual_validation_ids:
            raise ValueError("manual train and validation IDs must be disjoint")
        if manual_role not in {None, "train", "val"}:
            raise ValueError("manual annotation role must be train or val")
        if manual_annotation_scope not in {None, 'human_annotation_assistance_only'}:
            raise ValueError('unknown manual annotation scope')
        auxiliary = manual_annotation_scope == 'human_annotation_assistance_only'
        self.rows = []
        for record in records:
            annotation = by_id.get(record.frame_id)
            if annotation is None or annotation.status not in {"pos", "negative"}:
                continue
            from pallet.data.eligibility import require_eligible
            require_eligible(record)
            if augmentation and annotation.ignore_regions:
                continue
            if require_review:
                manual_train = record.frame_id in manual_training_ids
                manual_validation = record.frame_id in manual_validation_ids
                if manual_train and ((not auxiliary and annotation.split != 'train') or manual_role == 'val'):
                    raise ValueError(f'manual-training manifest includes a non-train frame or wrong role: {record.frame_id}')
                if manual_validation and ((not auxiliary and annotation.split != 'train') or manual_role == 'train'):
                    raise ValueError(f'manual validation manifest includes a non-validation frame or wrong role: {record.frame_id}')
                if not manual_train and not manual_validation and not is_resolved(
                        annotation, require_blind=annotation.split in {'val', 'test'}):
                    continue
                if record.source_sha256 and annotation.source_anchor_hash != record.source_sha256:
                    raise ValueError(f'annotation source mismatch: {record.frame_id}')
            self.rows.append((record, annotation))
        self.normalization = normalization
        self.size = size
        self.augmentation = augmentation
        self.mosaic = mosaic
        self.spatial_augmentation = spatial_augmentation

    def __len__(self):
        return len(self.rows)

    def _read_one(self, index, tile_size):
        record, annotation = self.rows[index]
        raw = load_frame(record)
        h, w = raw.shape[:2]
        if (annotation.width, annotation.height) != (w, h):
            raise ValueError(f"annotation dimensions disagree with sensor frame {record.frame_id}")
        normalized = apply_normalization(raw, self.normalization)
        if self.augmentation and not self.spatial_augmentation:
            normalized = augment_sensor(normalized)
        image, scale, (left, top) = letterbox_float(normalized, tile_size)
        boxes = []
        for box in annotation.boxes:
            cx = ((box.x + box.width / 2) * scale + left) / tile_size
            cy = ((box.y + box.height / 2) * scale + top) / tile_size
            boxes.append((cx, cy, box.width * scale / tile_size, box.height * scale / tile_size))
        boxes = torch.tensor(boxes, dtype=torch.float32).reshape(-1, 4)
        if self.augmentation and self.spatial_augmentation:
            if self.spatial_augmentation == "rfdetr":
                image, boxes = augment_rf_float(image, boxes)
            else:
                image, boxes = augment_spatial_float(image, boxes)
        return image, boxes, SampleMeta(
            record.frame_id, (h, w), scale, (left, top)
        )

    def __getitem__(self, index):
        if not self.mosaic or np.random.random() >= 0.5 or len(self.rows) < 4:
            return self._read_one(index, self.size)
        tile_size = self.size // 2
        if tile_size * 2 != self.size:
            raise ValueError("mosaic requires an even input size")
        indices = [index] + np.random.choice(len(self.rows), 3, replace=False).tolist()
        image = torch.zeros((4, self.size, self.size), dtype=torch.float32)
        boxes = []
        metadata = None
        for quadrant, row_index in enumerate(indices):
            tile, local_boxes, local_meta = self._read_one(row_index, tile_size)
            top = tile_size * (quadrant // 2)
            left = tile_size * (quadrant % 2)
            image[:, top:top + tile_size, left:left + tile_size] = tile
            local_boxes[:, :2] = local_boxes[:, :2] * 0.5 + torch.tensor([left, top]) / self.size
            local_boxes[:, 2:] *= 0.5
            boxes.append(local_boxes)
            if quadrant == 0:
                metadata = local_meta
        return image, torch.cat(boxes), metadata


def augment_rf_float(image, boxes):
    """RF native optional flip probability .5 with synchronized float/mask boxes.

    Fixed sensor letterbox replaces native direct square resize and random
    resize/crop. Scale jitter and multi-scale are research-disabled at640.
    """
    if np.random.random() < .5:
        image = image.flip(-1)
        boxes = boxes.clone()
        boxes[:, 0] = 1 - boxes[:, 0]
    return image, boxes


def augment_spatial_float(image, boxes):
    """Upstream default scale/translate/flip geometry on float sensor channels.

    Defaults degrees/shear/perspective are zero. Bilinear supported-value
    interpolation and nearest validity use one common spatial grid. Bounding
    boxes use upstream affine candidate thresholds (wh>2, area>.1, aspect<100).
    """
    size = image.shape[-1]
    scale = float(np.random.uniform(.5, 1.5))
    tx, ty = np.random.uniform(-.1, .1, 2) * size
    # Output pixel centers map back through the affine transform to input.
    coord = torch.arange(size, dtype=image.dtype) + .5
    yy, xx = torch.meshgrid(coord, coord, indexing="ij")
    grid = torch.stack((((xx - size / 2 - tx) / scale + size / 2) * 2 / size - 1,
                        ((yy - size / 2 - ty) / scale + size / 2) * 2 / size - 1), dim=-1)[None]
    support = F.grid_sample(image[None, 2:], grid, align_corners=False)
    values = F.grid_sample(image[None, :2] * image[None, 2:], grid,
                           align_corners=False) / support.clamp_min(1e-6)
    valid = F.grid_sample(image[None, 2:], grid, mode="nearest", align_corners=False)
    transformed = torch.cat((values * valid, valid), dim=1)[0]
    if len(boxes):
        center = (boxes[:, :2] * size - size / 2) * scale + size / 2 + boxes.new_tensor([tx, ty])
        wh = boxes[:, 2:] * size * scale
        lo = (center - wh / 2).clamp(0, size)
        hi = (center + wh / 2).clamp(0, size)
        new_wh = hi - lo
        area_ratio = new_wh.prod(1) / wh.prod(1).clamp_min(1e-6)
        aspect = torch.maximum(new_wh[:, 0] / new_wh[:, 1].clamp_min(1e-6),
                               new_wh[:, 1] / new_wh[:, 0].clamp_min(1e-6))
        keep = (new_wh.min(1).values > 2) & (area_ratio > .1) & (aspect < 100)
        boxes = torch.cat(((lo + hi) / (2 * size), new_wh / size), dim=1)[keep]
    if np.random.random() < .5:
        transformed = transformed.flip(-1)
        boxes[:, 0] = 1 - boxes[:, 0]
    return transformed, boxes


def augment_sensor(frame: np.ndarray) -> np.ndarray:
    """Sensor-specific intensity, missing-data and resolution perturbations."""
    output = np.asarray(frame, dtype=np.float32).copy()
    height, width = output.shape[:2]
    if np.random.random() < 0.15 and np.any(output[...,2]>0) and np.any(output[...,3]>0):
        modality = 0 if np.random.random() < 0.5 else 1
        output[..., modality] = 0
        output[..., modality + 2] = 0
    if np.random.random() < 0.35:
        hole_w = max(1, int(width * np.random.uniform(0.02, 0.16)))
        hole_h = max(1, int(height * np.random.uniform(0.02, 0.16)))
        left = np.random.randint(0, width - hole_w + 1)
        top = np.random.randint(0, height - hole_h + 1)
        output[top:top + hole_h, left:left + hole_w, 0] = 0
        output[top:top + hole_h, left:left + hole_w, 2] = 0
    if np.random.random() < 0.5:
        output[..., 1] = np.clip(output[..., 1] * np.random.uniform(0.7, 1.3), 0, 1)
    if np.random.random() < 0.3:
        output[..., :2] = np.round(output[..., :2] * 255) / 255
    if np.random.random() < 0.4:
        ratio = np.random.uniform(0.55, 0.95)
        target = (max(1, int(height * ratio)), max(1, int(width * ratio)))
        tensor = torch.from_numpy(np.ascontiguousarray(output.transpose(2, 0, 1)))[None]
        values = F.interpolate(F.interpolate(tensor[:, :2], size=target, mode="bilinear",
                                             align_corners=False), size=(height, width),
                               mode="bilinear", align_corners=False)
        valid = F.interpolate(F.interpolate(tensor[:, 2:], size=target, mode="nearest"),
                              size=(height, width), mode="nearest")
        output = torch.cat((values * valid, valid), dim=1)[0].permute(1, 2, 0).numpy()
    output[..., :2] *= output[..., 2:]
    return output


def collate_pallet(batch):
    images, boxes, metadata = zip(*batch)
    labels = [torch.zeros((len(box), 1), dtype=torch.float32) for box in boxes]
    indices = [torch.full((len(box),), idx, dtype=torch.long) for idx, box in enumerate(boxes)]
    return {
        "img": torch.stack(images),
        "batch_idx": torch.cat(indices),
        "cls": torch.cat(labels),
        "bboxes": torch.cat(boxes),
        "meta": metadata,
    }


def restore_boxes(boxes: np.ndarray, meta: SampleMeta, size: int = 640) -> np.ndarray:
    """Map model XYXY pixel boxes from letterboxed input to raw sensor pixels."""
    arr = np.asarray(boxes, dtype=np.float32).reshape(-1, 4).copy()
    left, top = meta.padding
    arr[:, [0, 2]] = (arr[:, [0, 2]] - left) / meta.scale
    arr[:, [1, 3]] = (arr[:, [1, 3]] - top) / meta.scale
    h, w = meta.original_size
    arr[:, [0, 2]] = np.clip(arr[:, [0, 2]], 0, w)
    arr[:, [1, 3]] = np.clip(arr[:, [1, 3]], 0, h)
    return arr
