"""Formatter for person detection processor results."""

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


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

    has_person = result.data.get("has_person", False)
    detection_percentage = result.data.get("detection_percentage", 0.0)
    frames_with_person = result.data.get("frames_with_person", 0)
    total_frames = result.data.get("total_frames", 0)

    if has_person:
        summary = f"PERSON: detected in {detection_percentage:.1f}% of frames"
    else:
        summary = "PERSON: not detected"

    content_parts = []
    if has_person:
        content_parts.append(f"Person presence: {detection_percentage:.1f}%")
        content_parts.append(f"Frames with person: {frames_with_person}/{total_frames}")

    content = "\n".join(content_parts)

    detail_parts = [
        "success",
        f"has_person={has_person}",
        f"detection_percentage={detection_percentage:.1f}%",
    ]

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

    vlm_context = f"PERSON_DETECTION: {detection_percentage:.1f}%"

    return FormattedOutput(
        summary_line=summary,
        content_text=content,
        detail_line=" | ".join(detail_parts),
        is_empty=not has_person,
        rag_metadata={
            "visual_has_person": has_person,
            "visual_person_percentage": detection_percentage,
            "visual_person_frame_count": frames_with_person,
        },
        vlm_context=vlm_context,
    )
