# apps/core/utils.py
import os
import stat


def ensure_dir_permissions(directories):
    """
    确保目录存在且具有写入权限
    """
    for dir_path in directories:
        # 1. 确保目录存在
        if not os.path.exists(dir_path):
            try:
                os.makedirs(dir_path, exist_ok=True)
                print(f"创建目录: {dir_path}")
            except OSError as e:
                raise PermissionError(f"无法创建目录 {dir_path}: {e}")

        # 2. 检查是否为目录
        if not os.path.isdir(dir_path):
            raise PermissionError(f"路径不是目录: {dir_path}")

        # 3. 检查写入权限
        if not os.access(dir_path, os.W_OK):
            # 尝试修改权限
            try:
                os.chmod(dir_path, stat.S_IWUSR | stat.S_IRUSR | stat.S_IXUSR)
                print(f"修改目录权限: {dir_path}")
            except OSError:
                raise PermissionError(f"目录不可写且无法修改权限: {dir_path}")

        # 4. 验证写入测试文件
        test_file = os.path.join(dir_path, ".permission_test")
        try:
            with open(test_file, "w") as f:
                f.write("test")
            os.remove(test_file)
        except IOError:
            raise PermissionError(f"无法在目录中创建文件: {dir_path}")

    return True
