"""SAM3 candidate generation from sensor visualizations; never assigns truth labels."""

from __future__ import annotations

from pathlib import Path
import sys

import numpy as np
from PIL import Image

from pallet.annotation import Box, Provenance, load_jsonl, merge_proposals, save_jsonl
from pallet.data import canonical_records, load_frame, scan_dataset


SAM3_PROJECT = Path("/root/private/project/zero_shot_segmentation")
SAM3_WEIGHTS = SAM3_PROJECT / "models/sam3/sam3.pt"


def _display_channel(values: np.ndarray, mask: np.ndarray, *, invert=False) -> np.ndarray:
    valid = mask > 0
    if not valid.any():
        return np.zeros(values.shape, dtype=np.uint8)
    samples = values[valid]
    low, high = np.percentile(samples, [1, 99])
    if high <= low:
        return np.zeros(values.shape, dtype=np.uint8)
    scaled = np.clip((values - low) / (high - low), 0, 1)
    if invert:
        scaled = 1 - scaled
    return np.where(valid, np.uint8(255 * scaled), 0)


def sensor_visualization(frame: np.ndarray) -> Image.Image:
    """Make a display-only pseudo-color image; measurement floats stay untouched."""
    depth, intensity, valid_d, valid_i = [frame[..., idx] for idx in range(4)]
    d = _display_channel(depth, valid_d, invert=True)
    i = _display_channel(intensity, valid_i)
    rgb = np.stack((i, d, np.maximum(i // 2, d // 2)), axis=-1)
    return Image.fromarray(rgb, "RGB")


def _sam3_service(device):
    if not SAM3_WEIGHTS.is_file():
        raise FileNotFoundError(f"SAM3 checkpoint missing: {SAM3_WEIGHTS}")
    sys.path.insert(0, str(SAM3_PROJECT))
    sys.path.insert(0, str(SAM3_PROJECT / "third_party/sam3"))
    from zss_demo.sam3_adapter import Sam3Service
    # Upstream builder accepts the literal "cuda"; "cuda:0" leaves weights on CPU.
    if str(device).startswith("cuda"):
        import torch
        torch.cuda.set_device(torch.device(device))
        device = "cuda"
    return Sam3Service(checkpoint_path=str(SAM3_WEIGHTS), device=device)


def generate_sam3_proposals(root, annotation_path, *, split="train", limit=None,
                            device="cuda:0", prompts=("a pallet", "stacked pallets")):
    """Write resumable proposals only for unreviewed source frames.

    Independent val/test references must be made from original views, never
    from detections by a model trained on the experiment's source split.
    """
    if split not in {"train", "val", "test"}:
        raise ValueError("invalid split")
    annotations = load_jsonl(annotation_path)
    records = canonical_records(scan_dataset(root))
    eligible = [record for record in records
                if record.frame_id in annotations.frames
                and annotations.frames[record.frame_id].split == split
                and annotations.frames[record.frame_id].status == "unreviewed"
                and len(annotations.frames[record.frame_id].provenance) == 1]
    if limit is not None:
        eligible = eligible[:limit]
    if not eligible:
        return {"requested": 0, "proposed": 0, "errors": []}
    predictor = _sam3_service(device)
    proposed, errors = 0, []
    for idx, record in enumerate(eligible):
        try:
            image = sensor_visualization(load_frame(record))
            candidates = []
            for prompt in prompts:
                candidates.extend(predictor.segment_by_text(image, prompt, top_k=8))
            boxes = []
            for result in sorted(candidates, key=lambda item: item.score, reverse=True):
                if result.box_xyxy is None or result.score < 0.35:
                    continue
                x1, y1, x2, y2 = result.box_xyxy
                x1, y1 = max(0, x1), max(0, y1)
                x2, y2 = min(image.width, x2), min(image.height, y2)
                if x2 <= x1 or y2 <= y1:
                    continue
                if any(_box_iou((x1, y1, x2, y2), old) > 0.75 for old in boxes):
                    continue
                boxes.append((x1, y1, x2, y2))
            merge_proposals(annotations, {record.frame_id: [Box(x1, y1, x2 - x1, y2 - y1)
                                                              for x1, y1, x2, y2 in boxes]},
                            provenance=Provenance("sam3", model=str(SAM3_WEIGHTS)))
            proposed += 1
        except Exception as exc:
            errors.append({"frame_id": record.frame_id, "error": str(exc)})
        if (idx + 1) % 25 == 0:
            save_jsonl(annotations, annotation_path)
    save_jsonl(annotations, annotation_path)
    return {"requested": len(eligible), "proposed": proposed, "errors": errors}


def _box_iou(box, other):
    x1, y1 = max(box[0], other[0]), max(box[1], other[1])
    x2, y2 = min(box[2], other[2]), min(box[3], other[3])
    intersection = max(0, x2 - x1) * max(0, y2 - y1)
    area_a = (box[2] - box[0]) * (box[3] - box[1])
    area_b = (other[2] - other[0]) * (other[3] - other[1])
    return intersection / (area_a + area_b - intersection) if area_a + area_b > intersection else 0
