import os
from pathlib import Path
from typing import Tuple


def get_relative_path(file_path: Path, source_path: Path) -> Path:
    return file_path.relative_to(source_path)


def get_output_filename(file_path: Path, quality: int) -> Path:
    stem = file_path.stem
    return Path(f"{stem}_webp_q{quality}.webp")


def create_output_directory(output_path: Path) -> bool:
    try:
        output_path.mkdir(parents=True, exist_ok=True)
        return True
    except Exception:
        return False


def get_unique_output_file(output_file: Path) -> Path:
    if not output_file.exists():
        return output_file
    stem = output_file.stem
    suffix = output_file.suffix
    parent = output_file.parent
    counter = 1
    while True:
        candidate = parent / f"{stem}_{counter}{suffix}"
        if not candidate.exists():
            return candidate
        counter += 1


def save_image(
    image_bytes: bytes,
    source_file: Path,
    source_path: Path,
    output_folder: Path,
    quality: int
) -> Tuple[bool, Path]:
    try:
        relative_path = get_relative_path(source_file, source_path)
        
        output_subfolder = output_folder
        parent_dir = relative_path.parent
        if parent_dir and parent_dir != Path('.'):
            output_subfolder = output_folder / parent_dir
        
        create_output_directory(output_subfolder)
        
        output_filename = get_output_filename(relative_path, quality)
        output_file = output_subfolder / output_filename
        output_file = get_unique_output_file(output_file)
        
        with open(output_file, 'wb') as f:
            f.write(image_bytes)
        
        return True, output_file
        
    except Exception:
        return False, source_file