# -*- coding: utf-8 -*-
"""
上传模块测试
所有测试在"测试目录 SIGN"文件夹内执行
"""
import pytest
import asyncio
import time
from typing import Tuple

from v123pan import V123Pan
from tests import config
from tests.utils import TestUtils


pytestmark = pytest.mark.integration


class TestUpload:
    """上传模块测试类"""

    @pytest.mark.asyncio
    async def test_create_directory(self, authorized_client_with_dir: Tuple[V123Pan, int]):
        """测试创建目录"""
        client, dir_id = authorized_client_with_dir

        unique_name = f"pytest_dir_{int(time.time())}"
        result = await client.directory(unique_name, dir_id)

        assert TestUtils.validate_response(result)
        assert TestUtils.validate_field(result, "data.dirID", int)

        sub_dir_id = result["data"]["dirID"]
        assert sub_dir_id > 0

        # 清理
        await client.delete([sub_dir_id])

    @pytest.mark.asyncio
    async def test_file_quick_transfer(self, authorized_client_with_dir: Tuple[V123Pan, int]):
        """测试文件秒传"""
        client, dir_id = authorized_client_with_dir

        unique_filename = f"pytest_file_{int(time.time())}.txt"
        result = await client.file(
            dir_id,
            unique_filename,
            "d41d8cd98f00b204e9800998ecf8427e",
            0
        )

        assert TestUtils.validate_response(result)
        assert TestUtils.validate_field(result, "data.fileID", int)

        file_id = result["data"]["fileID"]
        assert file_id > 0

        # 清理
        await client.delete([file_id])

    @pytest.mark.asyncio
    async def test_file_create_need_upload(self, authorized_client_with_dir: Tuple[V123Pan, int]):
        """测试需要上传的文件创建"""
        client, dir_id = authorized_client_with_dir

        unique_filename = f"pytest_upload_{int(time.time())}.txt"
        result = await client.file(
            dir_id,
            unique_filename,
            "5d41402abc4b2a76b9719d911017c592",
            5
        )

        assert TestUtils.validate_response(result)

        if not result["data"].get("reuse"):
            assert TestUtils.validate_field(result, "data.preuploadID", str)
            assert TestUtils.validate_field(result, "data.sliceSize", int)

    @pytest.mark.asyncio
    async def test_get_upload_url(self, authorized_client_with_dir: Tuple[V123Pan, int]):
        """测试获取上传 URL"""
        client, dir_id = authorized_client_with_dir

        unique_filename = f"pytest_url_{int(time.time())}.txt"

        # 先创建文件
        file_result = await client.file(
            dir_id,
            unique_filename,
            "5d41402abc4b2a76b9719d911017c592",
            5
        )

        if file_result["data"].get("reuse"):
            pytest.skip("文件秒传，无需上传")

        preupload_id = file_result["data"]["preuploadID"]

        # 获取上传 URL
        url_result = await client.url(preupload_id, 1)

        assert TestUtils.validate_response(url_result)
        assert TestUtils.validate_field(url_result, "data.presignedURL", str)

        presigned_url = url_result["data"]["presignedURL"]
        assert presigned_url.startswith("https://")

    @pytest.mark.asyncio
    async def test_complete_upload(self, authorized_client_with_dir: Tuple[V123Pan, int]):
        """测试完成上传"""
        client, dir_id = authorized_client_with_dir

        unique_filename = f"pytest_complete_{int(time.time())}.txt"

        # 先创建文件
        file_result = await client.file(
            dir_id,
            unique_filename,
            "5d41402abc4b2a76b9719d911017c592",
            5
        )

        if file_result["data"].get("reuse"):
            pytest.skip("文件秒传，无需完成上传")

        preupload_id = file_result["data"]["preuploadID"]

        # 完成上传（小文件同步完成）
        complete_result = await client.complete(preupload_id)

        assert TestUtils.validate_response(complete_result)
        assert TestUtils.validate_field(complete_result, "data.fileID", int)

        file_id = complete_result["data"]["fileID"]
        assert file_id > 0

        # 清理
        await client.delete([file_id])

    @pytest.mark.asyncio
    async def test_sha1_quick_transfer(self, authorized_client_with_dir: Tuple[V123Pan, int]):
        """测试 SHA1 秒传"""
        client, dir_id = authorized_client_with_dir

        unique_filename = f"pytest_sha1_{int(time.time())}.txt"
        result = await client.reuse(
            dir_id,
            unique_filename,
            "da39a3ee5e6b4b0d3255bfef95601890afd80709",
            0
        )

        assert TestUtils.validate_response(result)
        assert TestUtils.validate_field(result, "data.reuse", bool, True)
        assert TestUtils.validate_field(result, "data.fileID", int)

        file_id = result["data"]["fileID"]
        assert file_id > 0

        # 清理
        await client.delete([file_id])
