"""
Filename and path convention utilities for soundhub_utils.

License: BSD 3-Clause
"""
from typing import Optional
import re


def filename(
        name: str,
        directory: Optional[str] = None,
        start_byte: Optional[int] = None,
        end_byte: Optional[int] = None,
        start_time: int = None,
        end_time: Optional[int] = None,
        duration: Optional[int] = None,
        segment: Optional[int] = None,
        segment_prefix: str = 'n',
        ext: str = None,
        src_ext: Optional[str] = None) -> str:
    """
    Build a standardized filename from a base name and optional qualifiers.

    Applies qualifiers in this order: segment index, time range or byte range,
    then appends the extension and optional directory prefix.

    Args:
        name: Base filename (with or without extension)
        directory: Optional directory prefix prepended to the result
        start_byte: Start byte offset (used if no time args provided)
        end_byte: End byte offset
        start_time: Start time in seconds
        end_time: End time in seconds
        duration: Duration in seconds (used to compute end_time if not given)
        segment: Segment index, appended as <segment_prefix><segment>
        segment_prefix: Prefix character for segment index (default 'n')
        ext: Output file extension (leading dot stripped if present)
        src_ext: Extension to strip from name before building (defaults to ext)

    Returns:
        (str) filename
    """
    if ext:
        ext = re.sub(r'^\.', '', ext)
        if src_ext:
            src_ext = re.sub(r'^\.', '', src_ext)
        else:
            src_ext = ext
        name = re.sub(f'\\.{src_ext}$', '', name)
    if segment is not None:
        name = f'{name}.{segment_prefix}{segment}'
    if start_time or end_time or duration:
        if start_time is None:
            start_time = 0
        name = f'{name}.{start_time}'
        if (end_time is None) and duration:
            end_time = start_time + duration
        if end_time:
            name = f'{name}-{end_time}'
    elif start_byte is None:
        if end_byte:
            name = f'{name}.end_byte_{end_byte}'
    else:
        if end_byte:
            name = f'{name}.bytes_{start_byte}-{end_byte}'
        else:
            name = f'{name}.start_byte_{end_byte}'
    if ext:
        name = f'{name}.{ext}'
    if directory:
        name = f'{directory}/{name}'
    return name
