"""Exact toy geometry/postprocessing; no image, detector, weights or benchmark."""
from fractions import Fraction as Q
import platform


def box(values):
    result = tuple(Q(str(x)) for x in values)
    if len(result) != 4 or result[2] <= result[0] or result[3] <= result[1]:
        raise ValueError("Need positive-area continuous xyxy boxes")
    return result


def center_wh(b):
    x1, y1, x2, y2 = b
    return ((x1+x2)/2, (y1+y2)/2, x2-x1, y2-y1)


def corners(b):
    cx, cy, width, height = b
    return (cx-width/2, cy-height/2, cx+width/2, cy+height/2)


def iou(a, b):
    width = max(Q(0), min(a[2], b[2])-max(a[0], b[0]))
    height = max(Q(0), min(a[3], b[3])-max(a[1], b[1]))
    intersection = width*height
    area = lambda t: (t[2]-t[0])*(t[3]-t[1])
    return intersection/(area(a)+area(b)-intersection)


def nms(boxes, scores, classes, threshold, class_aware):
    # Deterministic original-index tie break, not a promise about library ties.
    order = sorted(range(len(boxes)), key=lambda i: (-scores[i], i))
    kept = []
    while order:
        current, *rest = order
        kept.append(current)
        order = [j for j in rest
                 if (class_aware and classes[j] != classes[current])
                 or iou(boxes[current], boxes[j]) <= threshold]
    return kept


def toy_ap(predicted, scores, ground_truth, threshold):
    """One image, one class, no ignore/crowd/difficult or maximum-detection rule.

    Match each detection's best-IoU GT, then reject already matched GT.
    Integrate the precision envelope at every recall change; not COCO AP.
    """
    if not ground_truth:
        raise ValueError("Toy AP requires at least one ground-truth box")
    order = sorted(range(len(predicted)), key=lambda i: (-scores[i], i))
    used, true_positives, flags, recalls, precisions = set(), 0, [], [], []
    for rank, i in enumerate(order, 1):
        overlaps = [iou(predicted[i], g) for g in ground_truth]
        best = max(range(len(overlaps)), key=lambda j: (overlaps[j], -j))
        is_tp = overlaps[best] >= threshold and best not in used
        if is_tp:
            used.add(best)
            true_positives += 1
        flags.append("TP" if is_tp else "FP")
        recalls.append(Q(true_positives, len(ground_truth)))
        precisions.append(Q(true_positives, rank))
    envelope = precisions[:]
    for i in range(len(envelope)-2, -1, -1):
        envelope[i] = max(envelope[i], envelope[i+1])
    ap, previous = Q(0), Q(0)
    for recall, precision in zip(recalls, envelope):
        ap += (recall-previous)*precision
        previous = recall
    return flags, recalls, precisions, ap


print(f"python={platform.python_version()} exact_fraction_geometry; no external packages")
a = box([0, 0, 2, 2])
b = box([0.2, 0.2, 2.2, 2.2])
d = box([3, 0, 5, 2])
assert corners(center_wh(b)) == b
assert iou(a, a) == 1 and iou(a, d) == 0 and iou(a, b) == Q(81, 119)
print(f"xyxy_round_trip=True IoU_identical=1 IoU_disjoint=0 IoU_shifted={iou(a,b)} ({float(iou(a,b)):.6f})")
boxes = [a, b, a, d]
scores = [Q('.9'), Q('.8'), Q('.85'), Q('.4')]
classes = [0, 0, 1, 0]
aware = nms(boxes, scores, classes, Q('.5'), True)
agnostic = nms(boxes, scores, classes, Q('.5'), False)
score_filter = [i for i, score in enumerate(scores) if score >= Q('.5')]
assert aware == [0, 2, 3] and agnostic == [0, 3]
assert score_filter == [0, 1, 2]
assert nms([a, a], [Q('.9'), Q('.8')], [0, 0], Q(1), True) == [0, 1]
print(f"score_threshold_0.5_indices={score_filter}; NMS_IoU_threshold_0.5_class_aware={aware}; class_agnostic={agnostic}")
print("NMS_suppresses_only_IoU_strictly_greater_than_threshold=True; exact_ties_use_original_index")
predicted = [a, b, box([6, 0, 8, 2]), d]
flags, recalls, precisions, ap = toy_ap(
    predicted, [Q('.9'), Q('.8'), Q('.7'), Q('.6')], [a, d], Q('.5'))
assert flags == ['TP', 'FP', 'FP', 'TP']
assert recalls == [Q('.5'), Q('.5'), Q('.5'), Q(1)]
assert precisions == [Q(1), Q(1,2), Q(1,3), Q(1,2)] and ap == Q(3,4)
assert toy_ap([], [], [a], Q('.5'))[-1] == 0
print(f"toy_match_flags={flags} recall={[str(x) for x in recalls]} precision={[str(x) for x in precisions]} all_point_interpolated_AP={ap}")
print("scope=hand-specified positive-area continuous xyxy boxes; exact IoU, score filter, class-aware/agnostic greedy NMS and one-image/single-class all-point interpolated AP; no trained detector, photo inference, anchor assignment implementation, COCO/VOC benchmark score, accuracy gain or latency measurement")
