import logging
import uuid
from pathlib import Path

import aiofiles
from fastapi import UploadFile

logger = logging.getLogger(__name__)

UPLOAD_DIR = Path.cwd() / ".nyahome" / "contents"

ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg", "gif"}


def s_get_safe_filename(original_name: str) -> str:
    """
    使用 uuid4 生成一个安全的文件名。

    Args:
        original_name: 完整的原始文件名。

    Raises:
        TypeError: 拓展名不在允许列表内。

    Returns:
        uuid4 生成的安全的文件名，后缀不变
    """
    suffix = original_name.rsplit(".", maxsplit=1)[-1]
    if suffix not in ALLOWED_EXTENSIONS:
        raise TypeError(f"给定文件的拓展名 {suffix} 不被允许。允许的文件拓展名：{ALLOWED_EXTENSIONS}")
    return f"{uuid.uuid4().hex}.{suffix}"


async def s_save_upload_file(filename: Path, file: UploadFile) -> None:
    try:
        async with aiofiles.open(filename, mode="wb") as f:
            await f.write(await file.read())
        logger.info(f"保存文件：{filename.name}")
    except Exception as e:
        logger.error(f"保存文件失败：{filename.name}")
        raise TypeError("保存文件时遇到未知错误，请检查。") from e
    finally:
        await file.close()
