"""Formatter for content safety processor results."""

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


@register_formatter("content_safety")
def format_content_safety(result: ProcessorResult) -> FormattedOutput:
    """Format content safety results for output."""
    if not result.success:
        return FormattedOutput(
            summary_line="SAFETY: failed",
            content_text="",
            detail_line=f"error={result.error}",
            is_empty=True,
        )

    has_safety_issues = result.data.get("has_safety_issues", False)
    safety_issues = result.data.get("safety_issues", [])
    frames_analyzed = result.data.get("frames_analyzed", 0)

    if has_safety_issues:
        summary = f"SAFETY: {len(safety_issues)} safety issues detected"
    else:
        summary = "SAFETY: content is safe"

    content_parts = []
    content_parts.append(f"Safety status: {'ISSUES FOUND' if has_safety_issues else 'SAFE'}")
    content_parts.append(f"Frames analyzed: {frames_analyzed}")

    if safety_issues:
        content_parts.append(f"\nSafety issues ({len(safety_issues)}):")
        for issue in safety_issues[:5]:  # Show first 5
            content_parts.append(f"  - {issue}")
        if len(safety_issues) > 5:
            content_parts.append(f"  ... and {len(safety_issues) - 5} more")

    content = "\n".join(content_parts)

    detail_parts = [
        "success",
        f"has_issues={has_safety_issues}",
        f"frames_analyzed={frames_analyzed}",
    ]

    if safety_issues:
        detail_parts.append(f"issues_count={len(safety_issues)}")

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

    if has_safety_issues:
        vlm_context = f"CONTENT_SAFETY: {len(safety_issues)} issues detected"
    else:
        vlm_context = "CONTENT_SAFETY: safe"

    return FormattedOutput(
        summary_line=summary,
        content_text=content,
        detail_line=" | ".join(detail_parts),
        is_empty=False,
        rag_metadata={
            "visual_safety_has_issues": has_safety_issues,
            "visual_safety_issues_count": len(safety_issues),
            "visual_safety_issues": ",".join(safety_issues) if safety_issues else "",
        },
        vlm_context=vlm_context,
    )
