"""Container format decision and validation."""

from .constants import FORMAT_INFO


def determine_output_format(stream_info, user_format, transcode_audio):
    """
    Decide which container format to use.

    Args:
        stream_info: Dict from get_stream_info().
        user_format: User‑requested format (or None).
        transcode_audio: Audio codec to transcode to (or None).

    Returns:
        A format name that exists in FORMAT_INFO.
    """
    if user_format:
        return user_format

    # If video or subtitles exist, use MKV (which supports everything).
    if stream_info['has_video'] or stream_info['has_subtitle']:
        return 'matroska'

    # Audio‑only: choose based on the current audio codec.
    audio_codec = stream_info.get('audio_codec', '')
    if audio_codec == 'mp3':
        return 'mp3'
    else:
        return 'mp4'  # .m4a


def validate_format_compatibility(format_name, stream_info, drop_video, drop_subs):
    """
    Ensure the chosen container can accommodate the streams we intend to keep.

    Raises:
        ValueError: If the format is incompatible with the intended streams.
    """
    info = FORMAT_INFO.get(format_name)
    if not info:
        print(f"Warning: Unknown format '{format_name}'. Proceeding, but may fail.")
        return

    if info['audio_only']:
        if stream_info['has_video'] and not drop_video:
            raise ValueError(
                f"Format '{format_name}' does not support video streams. "
                "Please use --drop-video or choose a container that supports video."
            )
        if stream_info['has_subtitle'] and not drop_subs:
            raise ValueError(
                f"Format '{format_name}' does not support subtitle streams. "
                "Please use --drop-subs or choose a container that supports subtitles."
            )
