"""Formatter for subtitle check processor results."""

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


@register_formatter("subtitle_check")
def format_subtitle_check(result: ProcessorResult) -> FormattedOutput:
    """Format subtitle check results for output."""
    if not result.success:
        return FormattedOutput(
            summary_line="SUBTITLES: failed",
            content_text="",
            detail_line=f"error={result.error}",
            is_empty=True,
        )

    has_subtitles = result.data.get("has_subtitles", False)
    subtitle_presence_score = result.data.get("subtitle_presence_score", 0.0)
    ocr_frame_coverage = result.data.get("ocr_frame_coverage", 0.0)

    if has_subtitles:
        summary = f"SUBTITLES: detected (confidence: {subtitle_presence_score:.2f})"
    else:
        summary = "SUBTITLES: not detected"

    content_parts = []
    content_parts.append(f"Subtitles present: {has_subtitles}")
    content_parts.append(f"Presence score: {subtitle_presence_score:.2f}")
    content_parts.append(f"OCR frame coverage: {ocr_frame_coverage:.1f}%")

    match_count = result.data.get("match_count", 0)
    total_ngrams = result.data.get("total_ngrams", 0)
    if total_ngrams > 0:
        match_pct = (match_count / total_ngrams) * 100
        content_parts.append(f"N-gram matches: {match_count}/{total_ngrams} ({match_pct:.1f}%)")

    content = "\n".join(content_parts)

    detail_parts = [
        "success",
        f"has_subtitles={has_subtitles}",
        f"score={subtitle_presence_score:.2f}",
    ]

    fuzzy_matching = result.metadata.get("fuzzy_matching")
    if fuzzy_matching is not None:
        detail_parts.append(f"fuzzy={fuzzy_matching}")

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

    vlm_context = (
        f"SUBTITLES: {'Yes' if has_subtitles else 'No'} (confidence: {subtitle_presence_score:.2f})"
    )

    return FormattedOutput(
        summary_line=summary,
        content_text=content,
        detail_line=" | ".join(detail_parts),
        is_empty=False,
        rag_metadata={
            "has_subtitles": has_subtitles,
            "subtitle_presence_score": subtitle_presence_score,
        },
        vlm_context=vlm_context,
    )
