"""Formatter for music detection processor results."""

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


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

    has_music = result.data.get("has_music", False)
    track_title = result.data.get("track_title", "")
    artist = result.data.get("artist", "")

    if has_music and track_title:
        if artist:
            summary = f"MUSIC: {track_title} - {artist}"
        else:
            summary = f"MUSIC: {track_title}"
    elif has_music:
        summary = "MUSIC: detected (unknown track)"
    else:
        summary = "MUSIC: none detected"

    content_parts = []
    if has_music:
        if track_title:
            content_parts.append(f"Track: {track_title}")
        if artist:
            content_parts.append(f"Artist: {artist}")

        for key in ["album", "genre", "year"]:
            value = result.data.get(key)
            if value:
                content_parts.append(f"{key.title()}: {value}")

    content = "\n".join(content_parts)

    detail_parts = ["success", f"has_music={has_music}"]
    if result.metadata:
        sample_duration = result.metadata.get("sample_duration")
        if sample_duration:
            detail_parts.append(f"sample_duration={sample_duration}s")

    if has_music and track_title:
        vlm_context = f"MUSIC: {track_title}"
    elif has_music:
        vlm_context = "MUSIC: music detected"
    else:
        vlm_context = "MUSIC: []"

    return FormattedOutput(
        summary_line=summary,
        content_text=content,
        detail_line=" | ".join(detail_parts),
        is_empty=not has_music,
        rag_metadata={
            "audio_has_music": has_music,
            "audio_music_track": track_title if has_music else "",
            "audio_music_artist": artist if has_music else "",
        },
        vlm_context=vlm_context,
    )
