"""Output filename generation."""

import os
import re

from .utils import apply_replacement, cleanup_good_chars, apply_template


def build_filename(track, idx, extension, args):
    """
    Build the complete output filename.

    Args:
        track: Dict of parsed track data.
        idx: Track index (1‑based).
        extension: File extension with leading dot (e.g., '.mp3').
        args: Parsed command‑line arguments.

    Returns:
        Sanitized filename.
    """
    # Prepare placeholder values.
    placeholders = {
        'tn': track.get('tn', ''),
        'an': track.get('an', ''),
        'al': track.get('al', ''),
        'date': track.get('date', ''),
        'ext': extension.lstrip('.'),   # e.g., 'mp3'
        'num': f"{idx:02d}"
    }

    # Apply the template.
    raw_filename = apply_template(args.output_template, placeholders)

    # If --number-tracks is used, prepend the track number.
    if args.number_tracks:
        raw_filename = f"{idx:02d} - {raw_filename}"

    # Apply character replacement if requested.
    if args.replace_bad_chars:
        clean_filename = apply_replacement(raw_filename,
                                           args.bad_chars,
                                           args.replacement_char)
        clean_filename = cleanup_good_chars(clean_filename, args.replacement_char)
    else:
        clean_filename = raw_filename
        # Warn about unsafe characters.
        forbidden = set(r'<>:"/\\|?*')
        if any(c in forbidden for c in clean_filename):
            print(f"Warning: Track {idx} filename contains unsafe characters "
                  f"({clean_filename}) – may cause filesystem errors.")

    return clean_filename
