import uuid
from datetime import datetime


def sanitize_filename(name: str) -> str:
    return name.replace(" ", "_").replace("/", "_")


def generate_uuid():
    return str(uuid.uuid4())


def build_s3_key(request, file_uuid: str):
    now = datetime.utcnow()
    safe_name = sanitize_filename(request.file_name)

    return (
        f"{request.tenant_name}/{request.clinic_id}/{request.patient_id}/"
        f"{request.document_type}/{now.year}/{now.month:02d}/"
        f"{file_uuid}_{safe_name}"
    )