from pathlib import Path
import glob


def get_target_path(tracking_file_source, target_dir):
    """
    get_target_path(tracking_file_source, target_dir)

    Returns the target path (mouse/session specific) for a source json.

    Required args:
        - tracking_file_source (Path): source json path
        - target_dir (Path)          : main target data directory
                                       (up to, but excluding mouse directories)

    Returns:
        - tracking_file_target (Path): target json path
    """
    
    # identify target directories
    source_file_name = Path(tracking_file_source).name

    file_name_tokens = str(source_file_name).split("_") 
    mouse_id = file_name_tokens[file_name_tokens.index("mouse") + 1] 
    sess_id = file_name_tokens[file_name_tokens.index("session") + 1]
    
    target_direc_pattern = Path(
        target_dir, 
        f"mouse_{mouse_id}", 
        f"ophys_session_{sess_id}", 
        f"ophys_experiment_*", 
        "processed"
        )

    target_direc = glob.glob(str(target_direc_pattern))
    
    if len(target_direc) == 0:
        raise OSError(
            f"No directory found with pattern: {target_direc_pattern}."
            )
    elif len(target_direc) > 1:
        target_matches = ", ".join([str(match) for match in target_direc])
        raise NotImplementedError(
            f"Multiple directories found with pattern: {target_direc_pattern}, "
            f"namely {target_matches}"
            )
    else:
        target_direc = target_direc[0]

    # set target path
    tracking_file_target = Path(target_direc, source_file_name)
    
    return tracking_file_target