"""Formatter for subtitle_presence results (generated by VideoRAG).

Note: subtitle_presence is not a standalone processor, but a result
generated by VideoRAG when comparing OCR and transcription results.
"""

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


@register_formatter("subtitle_presence")
def format_subtitle_presence(result: ProcessorResult) -> FormattedOutput:
    """Format subtitle presence results (same as subtitle_check)."""
    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_coverage = result.data.get("ocr_coverage", 0.0)
    matched_count = result.data.get("matched_count", 0)
    total_count = result.data.get("total_count", 0)
    detected_language = result.data.get("detected_language", "unknown")
    explanation = result.data.get("explanation", "")

    if has_subtitles:
        summary = (
            f"SUBTITLES: detected (score: {subtitle_presence_score:.2f}, lang: {detected_language})"
        )
    else:
        summary = f"SUBTITLES: not detected (score: {subtitle_presence_score:.2f})"

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

    if total_count > 0:
        match_pct = (matched_count / total_count) * 100
        content_parts.append(f"Matched tokens: {matched_count}/{total_count} ({match_pct:.1f}%)")

    if explanation:
        content_parts.append(f"\nExplanation: {explanation}")

    content = "\n".join(content_parts)

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

    if matched_count > 0:
        detail_parts.append(f"matched={matched_count}/{total_count}")

    if has_subtitles:
        vlm_context = f"SUBTITLES: detected (score: {subtitle_presence_score:.2f}, language: {detected_language})"
    else:
        vlm_context = f"SUBTITLES: not detected (score: {subtitle_presence_score:.2f})"

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