"""Formatter for frame extraction processor results."""

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


@register_formatter("frame_extraction")
def format_frame_extraction(result: ProcessorResult) -> FormattedOutput:
    """Format frame extraction results for output."""
    if not result.success:
        return FormattedOutput(
            summary_line="FRAMES: failed",
            content_text="",
            detail_line=f"error={result.error}",
            is_empty=True,
        )

    num_frames = result.data.get("num_frames", 0)  # Final frame count
    frames_extracted = result.data.get("frames_extracted", num_frames)  # Total before dedup
    frames_dir = result.data.get("frames_dir", "")
    duplicates_removed = result.data.get("duplicates_removed", 0)

    summary = f"FRAMES: {num_frames} frames"
    if duplicates_removed > 0:
        summary += f" (from {frames_extracted} extracted, {duplicates_removed} duplicates removed)"

    content_parts = []
    content_parts.append(f"Final frames: {num_frames}")
    if duplicates_removed > 0:
        content_parts.append(f"Extracted: {frames_extracted}")
        content_parts.append(f"Duplicates removed: {duplicates_removed}")
    if frames_dir:
        content_parts.append(f"Output directory: {frames_dir}")

    content = "\n".join(content_parts)

    detail_parts = ["success", f"num_frames={num_frames}"]

    if duplicates_removed > 0:
        detail_parts.append(f"extracted={frames_extracted}")
        detail_parts.append(f"duplicates_removed={duplicates_removed}")

    eliminate_duplicates = result.data.get("eliminate_duplicates_enabled")
    if eliminate_duplicates is not None:
        detail_parts.append(f"dedup_enabled={eliminate_duplicates}")

    vlm_context = f"FRAMES: {num_frames} frames extracted"

    return FormattedOutput(
        summary_line=summary,
        content_text=content,
        detail_line=" | ".join(detail_parts),
        is_empty=num_frames == 0,
        rag_metadata={
            "video_frame_count": num_frames,
            "video_frames_extracted": frames_extracted,
            "video_frames_duplicates_removed": duplicates_removed,
        },
        vlm_context=vlm_context,
    )
