def convert_results_to_coco(results):
    """
    Convert the 'results' list of dicts into COCO-format ground truth & predictions.
    """
    ground_truth_coco = {
        "images": [],
        "annotations": [],
        "categories": []
    }
    predictions_coco = []

    # Use sets/dicts for tracking
    cat_ids_seen = set()
    ann_id = 0  # unique annotation ID
    img_id = 0  # unique image ID

    for item in results:

        # 1) Add each image to ground_truth_coco if not seen yet
        ground_truth_coco["images"].append({
            "id": img_id,
            "file_name": f"image_{img_id}.jpg", # Dummy as we dont use these
            "width": item["img_width"],
            "height": item["img_height"]
        })

        # 2) Predictions to COCO "prediction format"
        for (box, label, score) in zip(item["pred_boxes"], item["pred_labels"], item["pred_scores"]):
            
            # box -> [x, y, w, h] if you used convert_boxes_coco
            x, y, w, h = box
            predictions_coco.append({
                "image_id": img_id,
                "category_id": label,    
                "bbox": [x, y, w, h],
                "score": float(score),
            })

            cat_ids_seen.add(label)

        # 3) Ground truth to COCO "annotation format"
        for (gt_box, gt_label) in zip(item["gt_boxes"], item["gt_labels"]):
            x, y, w, h = gt_box
            area = w * h
            
            ground_truth_coco["annotations"].append({
                "id": ann_id,
                "image_id": img_id,
                "category_id": gt_label, 
                "bbox": [x, y, w, h],
                "iscrowd": 0,
                "area": area
            })

            ann_id += 1
            cat_ids_seen.add(gt_label)

        img_id += 1

    # 4) Build "categories" array from all cat_ids_seen
    for cat_id in sorted(cat_ids_seen):
        ground_truth_coco["categories"].append({
            "id": cat_id,
            "name": f"class_{cat_id}"
        })

    return ground_truth_coco, predictions_coco
