"""Formatter for object detection processor results."""

from mini_videorag.core.formatters import register_formatter, FormattedOutput
from mini_videorag.core.processor import ProcessorResult


@register_formatter("object_detection")
def format_object_detection(result: ProcessorResult) -> FormattedOutput:
    """Format object detection results for output."""
    if not result.success:
        return FormattedOutput(
            summary_line="OBJECTS: failed",
            content_text="",
            detail_line=f"error={result.error}",
            is_empty=True,
        )

    unique_objects = result.data.get("unique_objects", [])
    object_counts = result.data.get("object_counts", {})
    total_detections = result.data.get("total_detections", 0)
    frames_analyzed = result.data.get("frames_analyzed", 0)

    if unique_objects:
        preview = ", ".join(unique_objects[:5])
        if len(unique_objects) > 5:
            preview += f" (+{len(unique_objects) - 5} more)"
        summary = f"OBJECTS: {preview}"
    else:
        summary = "OBJECTS: none detected"

    content_parts = []
    if object_counts:
        content_parts.append("Detected objects with counts:")
        for obj, count in sorted(object_counts.items(), key=lambda x: x[1], reverse=True):
            content_parts.append(f"  - {obj}: {count} occurrences")

    content = "\n".join(content_parts)

    detail_parts = [
        "success",
        f"unique_objects={len(unique_objects)}",
        f"total_detections={total_detections}",
        f"frames_analyzed={frames_analyzed}",
    ]

    confidence_threshold = result.metadata.get("confidence_threshold")
    if confidence_threshold:
        detail_parts.append(f"confidence_threshold={confidence_threshold}")

    if unique_objects:
        vlm_context = f"OBJECTS: {', '.join(unique_objects)}"
    else:
        vlm_context = ""  # Don't include if no objects

    return FormattedOutput(
        summary_line=summary,
        content_text=content,
        detail_line=" | ".join(detail_parts),
        is_empty=len(unique_objects) == 0,
        rag_metadata={
            "visual_objects_detected": (",".join(unique_objects) if unique_objects else ""),
            "visual_objects_count": len(unique_objects),
            "visual_objects_total_detections": total_detections,
        },
        vlm_context=vlm_context,
    )
