"""Formatter for OCR processor results."""

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


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

    all_text = result.data.get("all_text", [])
    frames_with_text = result.data.get("frames_with_text", 0)
    frames_processed = result.data.get("frames_processed", 0)
    text_count = result.data.get("text_count", len(all_text))

    # Get filtered tokens if available (enhanced OCR)
    filtered_tokens = result.data.get("filtered_tokens", [])
    filtered_token_count = result.data.get("filtered_token_count", len(filtered_tokens))

    display_text = filtered_tokens if filtered_tokens else all_text

    if display_text:
        text_preview = " ".join(display_text[:3])
        if len(text_preview) > 50:
            text_preview = text_preview[:50] + "..."
        summary = f"OCR: {text_preview}"
    else:
        summary = "OCR: no text detected"

    content = "\n".join(display_text) if display_text else ""

    detail_parts = ["success"]
    if frames_processed > 0:
        coverage = (frames_with_text / frames_processed) * 100
        detail_parts.append(
            f"frames_with_text={frames_with_text}/{frames_processed} ({coverage:.1f}%)"
        )

    if text_count > 0:
        detail_parts.append(f"text_count={text_count}")

    if filtered_token_count > 0:
        detail_parts.append(f"filtered_tokens={filtered_token_count}")

    detected_language = result.data.get("detected_language") or result.metadata.get(
        "detected_language"
    )
    if detected_language:
        detail_parts.append(f"detected_lang={detected_language}")

    languages = result.metadata.get("languages", [])
    if languages:
        detail_parts.append(f"languages={','.join(languages)}")

    vlm_parts = []
    if display_text:
        vlm_parts.append(f"OCR: {display_text}")
    else:
        vlm_parts.append("OCR: []")

    if detected_language:
        vlm_parts.append(f"DETECTED_LANGUAGE: {detected_language}")

    vlm_context = "\n".join(vlm_parts)

    return FormattedOutput(
        summary_line=summary,
        content_text=content,
        detail_line=" | ".join(detail_parts),
        is_empty=len(all_text) == 0,
        rag_metadata={
            "visual_ocr_text": ",".join(display_text) if display_text else "",
            "visual_ocr_language": detected_language or "",
            "visual_ocr_frame_coverage": (frames_with_text if frames_processed > 0 else 0),
            "visual_ocr_text_count": text_count,
        },
        vlm_context=vlm_context,
    )
