import os

from django.core.files.storage import FileSystemStorage
from django.utils.text import get_valid_filename


class ReleaseFileStorage(FileSystemStorage):
    def get_available_name(self, name, max_length=None):
        return name


release_file_storage = ReleaseFileStorage()

RELEASE_FILE_BY_URL_FIELD = {
    "windows_download_url": "windows_download_file",
    "macos_download_url": "macos_download_file",
    "linux_download_url": "linux_download_file",
    "source_code_url": "source_code_file",
}

RELEASE_ASSET_KEY_BY_URL_FIELD = {
    "windows_download_url": "windows",
    "macos_download_url": "macos",
    "linux_download_url": "linux",
    "source_code_url": "source",
}

URL_FIELD_BY_ASSET_KEY = {
    v: k for k, v in RELEASE_ASSET_KEY_BY_URL_FIELD.items()
}

FILE_FIELD_BY_ASSET_KEY = {
    asset: RELEASE_FILE_BY_URL_FIELD[url_field]
    for url_field, asset in RELEASE_ASSET_KEY_BY_URL_FIELD.items()
}

RELEASE_ASSET_KEYS = frozenset(FILE_FIELD_BY_ASSET_KEY.keys())

RELEASE_FILE_HELP_TEXT = (
    "Optional. Served from this site when the matching URL above is empty. "
    "To remove an uploaded file, check Clear, then Save — the file is deleted from the server. "
    "Any file type and size are allowed; large uploads may require web server limits."
)

RELEASE_ORIGINAL_FILENAME_FIELDS = {
    "windows_download_file": "windows_download_filename",
    "macos_download_file": "macos_download_filename",
    "linux_download_file": "linux_download_filename",
    "source_code_file": "source_code_filename",
}

RELEASE_ORIGINAL_FILENAME_BY_ASSET = {
    RELEASE_ASSET_KEY_BY_URL_FIELD[url_field]: RELEASE_ORIGINAL_FILENAME_FIELDS[file_field]
    for url_field, file_field in RELEASE_FILE_BY_URL_FIELD.items()
}


def _release_file_path(instance, filename, platform):
    if instance.sub_product_id:
        base = f"{instance.sub_product.main_product.slug}/{instance.sub_product.slug}"
    else:
        base = instance.main_product.slug
    version_part = (instance.version or "release").replace("/", "-")
    safe_name = get_valid_filename(os.path.basename(filename))
    return f"releases/{base}/{version_part}/{platform}/{safe_name}"


def release_windows_file_upload_to(instance, filename):
    return _release_file_path(instance, filename, "windows")


def release_macos_file_upload_to(instance, filename):
    return _release_file_path(instance, filename, "macos")


def release_linux_file_upload_to(instance, filename):
    return _release_file_path(instance, filename, "linux")


def release_source_file_upload_to(instance, filename):
    return _release_file_path(instance, filename, "source")


release_file_upload_to = release_windows_file_upload_to
