"""Formatter for brand detection processor results."""

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


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

    brands = result.data.get("brands_detected", [])
    brand_counts = result.data.get("brand_counts", {})
    threshold = result.metadata.get("confidence_threshold", 0.3)
    frames_analyzed = result.data.get("frames_analyzed", 0)

    if brands:
        summary = f"BRANDS: {', '.join(brands)}"
    else:
        summary = "BRANDS: none detected"

    content_parts = []
    if brand_counts:
        content_parts.append("Detected brands with counts:")
        for brand, count in sorted(brand_counts.items(), key=lambda x: x[1], reverse=True):
            content_parts.append(f"  - {brand}: {count} occurrences")
    content = "\n".join(content_parts)

    detail_parts = [
        "success",
        f"confidence_threshold={threshold}",
        f"frames_analyzed={frames_analyzed}",
    ]
    if brand_counts:
        total_detections = sum(brand_counts.values())
        detail_parts.append(f"total_detections={total_detections}")

    if brands:
        vlm_context = f"BRANDS: {', '.join(brands)}"
    else:
        vlm_context = ""

    return FormattedOutput(
        summary_line=summary,
        content_text=content,
        detail_line=" | ".join(detail_parts),
        is_empty=len(brands) == 0,
        rag_metadata={
            "visual_brands_detected": ",".join(brands) if brands else "",
            "visual_brands_count": len(brands),
            "visual_brands_total_detections": (sum(brand_counts.values()) if brand_counts else 0),
        },
        vlm_context=vlm_context,
    )
