"""Metadata selection and building."""


def select_album_value(track, input_metadata, args):
    """
    Determine the album value according to precedence.

    Precedence: --album > %al > original album > original title > None.

    Args:
        track: Dict of parsed track data.
        input_metadata: Dict from get_metadata().
        args: Parsed command‑line arguments.

    Returns:
        Album string or None.
    """
    original_album = input_metadata.get('album')
    original_title = input_metadata.get('title')

    if args.album:
        return args.album
    elif track.get('al'):
        return track.get('al')
    elif original_album:
        return original_album
    elif original_title:
        return original_title
    else:
        return None


def select_comment_value(input_metadata, args):
    """
    Determine the comment value according to precedence.

    Precedence: --no-comment > --comment > --merge-comments >
    --comment-stream > first comment from file.

    Args:
        input_metadata: Dict from get_metadata().
        args: Parsed command‑line arguments.

    Returns:
        Comment string or None.
    """
    original_comments = input_metadata.get('comments', [])

    if args.no_comment:
        return None
    elif args.comment:
        return args.comment
    elif args.merge_comments and original_comments:
        separator = args.comment_separator if args.comment_separator else '; '
        comments_text = separator.join(comment for _, comment in original_comments)
        return comments_text if comments_text else None
    elif args.comment_stream is not None:
        if 0 <= args.comment_stream < len(original_comments):
            return original_comments[args.comment_stream][1]
        else:
            print(f"Warning: Stream {args.comment_stream} not found in comments list. "
                  f"Using first comment (if any).")
            if original_comments:
                return original_comments[0][1]
            return None
    elif original_comments:
        # Default: use the first comment.
        return original_comments[0][1]
    else:
        return None


def build_metadata_dict(track, idx, input_metadata, args):
    """
    Assemble the final metadata dictionary for FFmpeg.

    Args:
        track: Dict of parsed track data.
        idx: Track index (1‑based).
        input_metadata: Dict from get_metadata().
        args: Parsed command‑line arguments.

    Returns:
        Dict with metadata fields (empty values removed).
    """
    album_value = select_album_value(track, input_metadata, args)
    comment_value = select_comment_value(input_metadata, args)

    metadata = {
        'title': track.get('tn', ''),
        'artist': track.get('an', ''),
        'album': album_value,
        'date': track.get('date', ''),
        'track': f"{idx:02d}",
        'comment': comment_value
    }

    # Remove empty fields.
    return {k: v for k, v in metadata.items() if v}
