"""Formatter for transcription processor results."""

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


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

    original_transcript = result.data.get("original_transcript", "")
    english_transcript = result.data.get("english_transcript", "")
    detected_language = result.data.get("detected_language", "unknown")

    if english_transcript:
        word_count = len(english_transcript.split())
        summary = f"TRANSCRIPTION: {word_count} words ({detected_language})"
    else:
        summary = "TRANSCRIPTION: empty"

    content_parts = []
    if original_transcript:
        content_parts.append(f"Original ({detected_language}):\n{original_transcript}\n")
    if english_transcript and english_transcript != original_transcript:
        content_parts.append(f"English:\n{english_transcript}")
    elif english_transcript:
        content_parts.append(english_transcript)

    content = "\n".join(content_parts)

    detail_parts = ["success", f"language={detected_language}"]
    if result.metadata:
        duration = result.metadata.get("duration")
        if duration:
            detail_parts.append(f"duration={duration:.1f}s")

    if english_transcript:
        vlm_context = f"TRANSCRIPTION: {english_transcript}"
    else:
        vlm_context = "TRANSCRIPTION: []"

    return FormattedOutput(
        summary_line=summary,
        content_text=content,
        detail_line=" | ".join(detail_parts),
        is_empty=len(english_transcript) == 0,
        rag_metadata={
            "transcription_text": english_transcript,
            "transcription_language": detected_language,
            "transcription_word_count": (
                len(english_transcript.split()) if english_transcript else 0
            ),
        },
        vlm_context=vlm_context,
    )
