from pathlib import Path
import click


def validate_json_yaml_filename(ctx, param, value):
    """Validate the name of the file has the proper extension and add the extension to the file object"""
    if value is None:
        return value

    if not hasattr(value, "name") or value.name == "<stdout>":
        # stdin/stdout case
        value.extension = "yaml"
        return value

    ALLOWED_EXTENSIONS = ["json", "yaml", "yml"]
    extension = Path(value.name).suffix[1:]

    if extension not in ALLOWED_EXTENSIONS:
        raise click.BadParameter(
            f"the extension of the file is '{extension}' while it should be one of {ALLOWED_EXTENSIONS}"
        )
    value.extension = extension
    return value