from __future__ import annotations

SUPPORTED = {"fruit": 1, "growth-tip": 2}


def execute(payload: dict) -> dict:
    if not isinstance(payload, dict):
        raise ValueError("payload must be an object")
    threshold = float(payload.get("threshold", 0.8))
    if not 0 <= threshold <= 1:
        raise ValueError("threshold must be between 0 and 1")
    candidates = []
    rejected = 0
    for observation in payload.get("observations", []):
        kind = observation.get("kind")
        confidence = float(observation.get("confidence", 0))
        position = observation.get("positionMm")
        if kind not in SUPPORTED or confidence < threshold or not isinstance(position, list) or len(position) != 3:
            rejected += 1
            continue
        candidates.append({
            "id": observation["id"], "kind": kind, "confidence": round(confidence, 4),
            "positionMm": [float(value) for value in position], "priority": SUPPORTED[kind],
        })
    candidates.sort(key=lambda item: (-item["priority"], -item["confidence"], item["id"]))
    counts = {kind: sum(item["kind"] == kind for item in candidates) for kind in SUPPORTED}
    accepted = bool(candidates)
    return {"component": "metafarmers/fruit-work-target-perception", "accepted": accepted,
            "status": "TARGETS_READY" if accepted else "NO_TARGETS", "target": "vpu",
            "frameId": str(payload.get("frameId", "unknown")), "candidates": candidates,
            "counts": counts, "rejected": rejected}
