"""Same-session candidate propagation from reviewed pallet boxes."""

from __future__ import annotations

import argparse
import json
from pathlib import Path
import sys

import cv2
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
from pallet.proposals import SAM3_PROJECT, _sam3_service, sensor_visualization


def mask_box(mask: np.ndarray, *, min_area=24):
    """Box the largest coherent instance; discard sparse, distant mask noise."""
    binary = (np.asarray(mask) > 0).astype(np.uint8)
    binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, np.ones((5, 5), np.uint8))
    count, _, stats, _ = cv2.connectedComponentsWithStats(binary, connectivity=8)
    if count <= 1:
        return None
    best = max(stats[1:], key=lambda row: int(row[cv2.CC_STAT_AREA]))
    x, y, width, height, area = [int(value) for value in best]
    if area < min_area or width <= 1 or height <= 1:
        return None
    return Box(x, y, width, height)


def _insid3_model(device):
    project = SAM3_PROJECT
    sys.path.insert(0, str(project / "third_party/INSID3"))
    sys.path.insert(0, str(project / "third_party/dinov3"))
    from models import build_insid3
    return build_insid3(model_size="large", image_size=512, svd_components=128,
                        device="cuda" if str(device).startswith("cuda") else "cpu",
                        mask_refiner="bilinear", model_dir=str(project / "models/insid3"))


def propagate(root, annotation_path, output, *, reference_id, limit=None, device="cuda:0"):
    annotations = load_jsonl(annotation_path)
    reference = annotations.frames[reference_id]
    if reference.split != "train" or reference.status != "pos" or len(reference.reviews) < 2:
        raise ValueError("few-shot reference needs a two-reviewed training-positive annotation")
    records = {row.frame_id: row for row in canonical_records(scan_dataset(root))}
    ref_record = records[reference_id]
    candidates = [record for record in records.values()
                  if record.frame_id != reference_id and record.group_id == ref_record.group_id
                  and record.frame_id in annotations.frames
                  and annotations.frames[record.frame_id].split == "train"
                  and annotations.frames[record.frame_id].status == "unreviewed"
                  and not any(p.source == "fewshot" for p in annotations.frames[record.frame_id].provenance)]
    if limit is not None:
        candidates = candidates[:limit]
    sam3 = _sam3_service(device)
    support_image = sensor_visualization(load_frame(ref_record))
    supports = []
    for box in reference.boxes:
        result = sam3.generate_reference_mask(
            support_image, box_xyxy=(box.x, box.y, box.x + box.width, box.y + box.height))
        if result is not None and result.mask.any():
            supports.append((Image.fromarray(result.mask.astype(np.uint8) * 255), box))
    if not supports:
        raise ValueError("SAM3 could not create any reference mask from reviewed boxes")
    predictor = _insid3_model(device)
    successful, errors = 0, []
    for index, record in enumerate(candidates):
        try:
            target_image = sensor_visualization(load_frame(record))
            if target_image.size != support_image.size:
                raise ValueError("reference and target sensor grids differ")
            boxes = []
            for support_mask, support_box in supports:
                predictor.set_reference(support_image, support_mask)
                predictor.set_target(target_image)
                prediction = predictor.segment()
                prediction = prediction.detach().cpu().numpy() if hasattr(prediction, "detach") else prediction
                proposal = mask_box(prediction, min_area=max(24, int(support_box.width * support_box.height * 0.05)))
                if proposal is not None and proposal.width * proposal.height < 5 * support_box.width * support_box.height:
                    boxes.append(proposal)
            merge_proposals(annotations, {record.frame_id: boxes},
                            provenance=Provenance("fewshot", actor="INSID3", model="DINOv3-L",
                                                  trained_group_ids=(reference.group_id,),
                                                  note=f"reference frame {reference_id}; proposal only"))
            successful += 1
        except Exception as exc:
            errors.append({"frame_id": record.frame_id, "error": str(exc)})
        if (index + 1) % 25 == 0:
            save_jsonl(annotations, output)
    save_jsonl(annotations, output)
    return {"reference_id": reference_id, "targets": len(candidates),
            "proposed": successful, "errors": errors, "output": str(output)}


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--root", default="/root/private/data/pallet")
    parser.add_argument("--annotations", default="outputs/annotations_pilot.jsonl")
    parser.add_argument("--output", default="outputs/annotations_fewshot.jsonl")
    parser.add_argument("--reference-id", required=True)
    parser.add_argument("--limit", type=int)
    parser.add_argument("--device", default="cuda:0")
    args = parser.parse_args()
    print(json.dumps(propagate(args.root, args.annotations, args.output,
                               reference_id=args.reference_id, limit=args.limit,
                               device=args.device), ensure_ascii=False))


if __name__ == "__main__":
    main()
