"""COCO-style box evaluation against independent machine reference labels."""

from __future__ import annotations

from contextlib import redirect_stdout
import io

import numpy as np
import torch
from torch.utils.data import DataLoader

from .dataset import collate_pallet, restore_boxes
from .loading import make_loader


def predict_boxes(model, image, meta, *, conf=0.001, size=640):
    return predict_batch_boxes(model, image, [meta], conf=conf, size=size)[0]


def predict_batch_boxes(model, images, metadata, *, conf=0.001, size=640):
    # Ensure Ultralytics selects the compiled torchvision NMS kernel, avoiding
    # thousands of Python/CUDA synchronizations at AP's low confidence floor.
    import torchvision
    from ultralytics.utils.nms import non_max_suppression

    if hasattr(model, "decode"):
        with torch.inference_mode():
            return [model.decode(images[index:index + 1], meta, conf=conf)
                    for index, meta in enumerate(metadata)]
    with torch.inference_mode():
        outputs = model(images)
        detections = non_max_suppression(outputs, conf_thres=conf, iou_thres=0.7,
                                         nc=1, max_det=300)
    if len(detections) != len(metadata):
        raise ValueError('prediction batch and coordinate metadata counts differ')
    results = []
    for detection, meta in zip(detections, metadata):
        rows = detection.cpu().numpy()
        boxes = restore_boxes(rows[:, :4], meta, size=size)
        results.append([(box.tolist(), float(row[4])) for box, row in zip(boxes, rows)])
    return results


def _iou(box, gt):
    x1, y1 = max(box[0], gt.x), max(box[1], gt.y)
    x2, y2 = min(box[2], gt.x + gt.width), min(box[3], gt.y + gt.height)
    intersection = max(0.0, x2 - x1) * max(0.0, y2 - y1)
    area = max(0.0, box[2] - box[0]) * max(0.0, box[3] - box[1])
    union = area + gt.width * gt.height - intersection
    return intersection / union if union > 0 else 0.0


def _count_matches(boxes, ground_truth, threshold, ignore_regions=()):
    used = set()
    tp = fp = 0
    for box, score in sorted(boxes, key=lambda pair: -pair[1]):
        if score < threshold:
            continue
        candidates = [(idx, _iou(box, gt)) for idx, gt in enumerate(ground_truth)
                      if idx not in used]
        idx, overlap = max(candidates, key=lambda item: item[1], default=(-1, 0.0))
        if overlap >= 0.5:
            used.add(idx)
            tp += 1
        else:
            if not _inside_ignored(box,ignore_regions):fp += 1
    return tp, fp, len(ground_truth) - tp


def _inside_ignored(box,regions):
    area=max(0,box[2]-box[0])*max(0,box[3]-box[1])
    if area<=0:return False
    for region in regions:
        x,y,w,h = (region.x,region.y,region.width,region.height) if hasattr(region,'x') else region
        intersection=max(0,min(box[2],x+w)-max(box[0],x))*max(0,min(box[3],y+h)-max(box[1],y))
        if intersection/area>=.5:return True
    return False


def _rates(rows):
    tp = sum(row["tp"] for row in rows)
    fp = sum(row["fp"] for row in rows)
    fn = sum(row["fn"] for row in rows)
    precision = tp / (tp + fp) if tp + fp else None
    recall = tp / (tp + fn) if tp + fn else None
    f1 = 2 * tp / (2 * tp + fp + fn) if tp + fn else None
    return {"images": len(rows), "objects": tp + fn, "true_positives": tp,
            "false_positives": fp, "missed": fn,
            "false_positives_per_frame": fp / len(rows) if rows else None,
            "precision": precision, "recall": recall, "f1": f1}


def _collect(model, dataset, device, batch_size, workers=0):
    loader = make_loader(dataset, batch_size=batch_size, workers=workers, device=device)
    collected = []
    for batch in loader:
        images = batch["img"].to(device, non_blocking=str(device).startswith('cuda'))
        predictions = predict_batch_boxes(model, images, batch["meta"], size=dataset.size)
        for meta, boxes in zip(batch["meta"], predictions):
            record, annotation = dataset.rows[len(collected)]
            boxes = [(box, score) for box, score in boxes
                     if box[2] > box[0] and box[3] > box[1]]
            collected.append((record, annotation, meta, boxes))
    return collected


def _select_threshold(collected):
    if not any(row.boxes for _, row, _, _ in collected):
        raise ValueError("threshold calibration requires positive validation references")
    detections=[];total=sum(len(row.boxes) for _,row,_,_ in collected)
    for _,row,_,boxes in collected:
        used=set()
        for box,score in sorted(boxes,key=lambda pair:-pair[1]):
            candidates=[(idx,_iou(box,gt)) for idx,gt in enumerate(row.boxes) if idx not in used]
            match,overlap=max(candidates,key=lambda pair:pair[1],default=(-1,0))
            hit=overlap>=.5
            if hit:used.add(match)
            if not hit and _inside_ignored(box,getattr(row,'ignore_regions',())):continue
            detections.append((float(score),int(hit)))
    if not detections:return .25
    detections.sort(key=lambda pair:-pair[0])
    scores=np.array([pair[0] for pair in detections])
    tp=np.cumsum([pair[1] for pair in detections])
    best=(-1.,.25)
    thresholds=np.unique(np.append(scores,.25))
    for threshold in thresholds:
        count=int(np.searchsorted(-scores,-threshold,side='right'))
        true=int(tp[count-1]) if count else 0
        f1=2*true/(total+count)
        best=max(best,(f1,float(threshold)))
    return best[1]


def _coco_ap(rows):
    from pycocotools.coco import COCO
    from pycocotools.cocoeval import COCOeval
    images=[];truth=[];predictions=[]
    for index,row in enumerate(rows,1):
        images.append({'id':index,'width':row.get('width',1),'height':row.get('height',1),
                       'file_name':row.get('frame_id',str(index))})
        for box in row.get('reference_boxes',[]):
            truth.append({'id':len(truth)+1,'image_id':index,'category_id':1,'bbox':box,
                          'area':box[2]*box[3],'iscrowd':0})
        for box in row.get('ignore_regions',[]):
            truth.append({'id':len(truth)+1,'image_id':index,'category_id':1,'bbox':box,
                          'area':box[2]*box[3],'iscrowd':1,'ignore':1})
        for prediction in row.get('predictions',[]):
            x1,y1,x2,y2=prediction['xyxy']
            predictions.append({'image_id':index,'category_id':1,'bbox':[x1,y1,x2-x1,y2-y1],
                                'score':prediction['score']})
    if not any(not row.get('iscrowd') for row in truth):return {'AP50':None,'AP75':None,'AP50_95':None}
    if not predictions:return {'AP50':0.,'AP75':0.,'AP50_95':0.}
    with redirect_stdout(io.StringIO()):
        coco=COCO();coco.dataset={'images':images,'annotations':truth,'categories':[{'id':1,'name':'pallet'}],'info':{}}
        coco.createIndex();result=coco.loadRes(predictions);evaluator=COCOeval(coco,result,'bbox')
        evaluator.evaluate();evaluator.accumulate();evaluator.summarize()
    return {'AP50':float(evaluator.stats[1]),'AP75':float(evaluator.stats[2]),'AP50_95':float(evaluator.stats[0])}


def _bootstrap(rows, samples, seed):
    groups = {}
    for row in rows:
        groups.setdefault(row["group_id"], []).append(row)
    if not groups:
        return {}
    rng = np.random.default_rng(seed)
    names = list(groups)
    metrics = {key: [] for key in ("precision", "recall", "f1", "false_positives_per_frame","AP50","AP75","AP50_95")}
    for _ in range(samples):
        draw = [row for name in rng.choice(names, size=len(names), replace=True)
                for row in groups[name]]
        rates = {**_rates(draw),**_coco_ap(draw)}
        for key, value in metrics.items():
            if rates[key] is not None:
                value.append(rates[key])
    return {key: [float(x) for x in np.percentile(values, [2.5, 97.5])]
            if values else None for key, values in metrics.items()}


def evaluate(model, dataset, *, device="cuda:0", batch_size=1, workers=0,
             confidence_threshold=0.25, calibration_dataset=None,
             bootstrap_samples=0, bootstrap_seed=42,
             reference="independently reviewed machine annotations"):
    """Evaluate AP and rates; calibrate a threshold only on validation data.

    Pass a validation ``calibration_dataset`` to maximize its F1 before scoring this
    dataset. ``bootstrap_samples`` resamples scene groups for operational-rate CIs.
    Undefined precision, recall, F1, or AP values are represented by None.
    """
    from pycocotools.coco import COCO
    from pycocotools.cocoeval import COCOeval

    if not 0 <= confidence_threshold <= 1 or bootstrap_samples < 0:
        raise ValueError("invalid confidence threshold or bootstrap sample count")
    model.eval().to(device)
    if calibration_dataset is not None:
        confidence_threshold = _select_threshold(
            _collect(model, calibration_dataset, device, batch_size, workers))
    collected = _collect(model, dataset, device, batch_size, workers)
    images, ground_truth, predictions, frames = [], [], [], []
    for image_id, (record, row, meta, boxes) in enumerate(collected, 1):
        images.append({"id": image_id, "width": meta.original_size[1],
                       "height": meta.original_size[0], "file_name": row.image})
        for gt in row.boxes:
            ground_truth.append({"id": len(ground_truth) + 1, "image_id": image_id,
                                 "category_id": 1, "bbox": [gt.x, gt.y, gt.width, gt.height],
                                 "area": gt.width * gt.height, "iscrowd": 0})
        for region in getattr(row,'ignore_regions',[]):
            ground_truth.append({'id':len(ground_truth)+1,'image_id':image_id,'category_id':1,
                                 'bbox':[region.x,region.y,region.width,region.height],
                                 'area':region.width*region.height,'iscrowd':1,'ignore':1})
        for box, score in boxes:
            x1, y1, x2, y2 = box
            predictions.append({"image_id": image_id, "category_id": 1,
                                "bbox": [x1, y1, x2 - x1, y2 - y1], "score": score})
        tp, fp, fn = _count_matches(boxes, row.boxes, confidence_threshold,getattr(row,'ignore_regions',()))
        frames.append({"frame_id": record.frame_id, "group_id": row.group_id,
                       'width':meta.original_size[1],'height':meta.original_size[0],
                       'tags':list(getattr(getattr(row,'scene',None),'tags',[])),
                       'ignore_regions':[[r.x,r.y,r.width,r.height] for r in getattr(row,'ignore_regions',[])],
                       "domain": getattr(row, "domain", getattr(record, "domain", "unknown")),
                       "reference_boxes": [[gt.x, gt.y, gt.width, gt.height]
                                           for gt in row.boxes],
                       "predictions": [{"xyxy": box, "score": score}
                                       for box, score in boxes],
                       "tp": tp, "fp": fp, "fn": fn})
    rates = _rates(frames)
    result = {"images": rates["images"], "objects": rates["objects"],
              "false_positives_per_frame": rates["false_positives_per_frame"],
              "recall_at_0.25_iou_0.5": rates["recall"]
              if confidence_threshold == 0.25 else None,
              "recall_at_threshold_iou_0.5": rates["recall"],
              "precision": rates["precision"], "f1": rates["f1"],
              "confidence_threshold": confidence_threshold,
              "threshold_source": "validation" if calibration_dataset is not None else "fixed",
              "reference": reference,
              "group_ids": sorted({row["group_id"] for row in frames}),
              "per_frame": frames}
    result["per_scene"] = {name: _rates([row for row in frames if row["group_id"] == name])
                           for name in result["group_ids"]}
    result["per_domain"] = {name: {**_rates([row for row in frames if row["domain"] == name]),
                                  **_coco_ap([row for row in frames if row['domain']==name])}
                            for name in sorted({row["domain"] for row in frames})}
    aliases={'stacked':{'stacked','stacked_pallets'},'occluded':{'occluded','partially_occluded'},
             'truncated':{'truncated','partially_truncated','edge_truncated','target_truncated'}}
    result['per_attribute']={name:{**_rates([r for r in frames if set(r['tags'])&tags]),
                                  **_coco_ap([r for r in frames if set(r['tags'])&tags])}
                             for name,tags in aliases.items()}
    if bootstrap_samples:
        result["bootstrap_ci"] = _bootstrap(frames, bootstrap_samples, bootstrap_seed)
        result['bootstrap_groups']=len(result['group_ids'])
        result['bootstrap_warning']='Fewer than two independent groups; interval does not quantify between-session variation' if len(result['group_ids'])<2 else None
    if not images or not ground_truth:
        result.update({"AP50": None, "AP75": None, "AP50_95": None})
        return result
    if not predictions:
        result.update({"AP50": 0.0, "AP75": 0.0, "AP50_95": 0.0})
        return result
    coco = COCO()
    coco.dataset = {"images": images, "annotations": ground_truth,
                    "categories": [{"id": 1, "name": "pallet"}], "info": {}, "licenses": []}
    with redirect_stdout(io.StringIO()):
        coco.createIndex()
        pred_coco = coco.loadRes(predictions)
        evaluator = COCOeval(coco, pred_coco, "bbox")
        evaluator.evaluate()
        evaluator.accumulate()
        evaluator.summarize()
    result.update({"AP50": float(evaluator.stats[1]), "AP75": float(evaluator.stats[2]),
                   "AP50_95": float(evaluator.stats[0])})
    return result
