#!/usr/bin/env python3
"""
测试POST文件API的脚本
"""

import requests
import json

# API基础URL
BASE_URL = "http://localhost:8000/api/v1"

def create_test_user():
    """创建测试用户"""
    register_data = {
        "username": "testuser",
        "email": "test@example.com",
        "password": "TestPass123!",
        "confirm_password": "TestPass123!"
    }

    try:
        print("创建测试用户...")
        reg_response = requests.post(f"{BASE_URL}/auth/register", json=register_data)
        print(f"注册状态码: {reg_response.status_code}")

        if reg_response.status_code == 201:
            reg_result = reg_response.json()
            if reg_result.get("success"):
                user_id = reg_result["data"]["user"]["id"]
                print(f"用户创建成功，ID: {user_id}")
                return user_id
            else:
                print(f"注册失败: {reg_result}")
        else:
            print(f"注册请求失败，状态码: {reg_response.status_code}")

        # 如果注册失败，尝试获取现有用户
        print("尝试获取现有用户...")
        login_data = {
            "username": "testuser",
            "password": "TestPass123!"
        }
        login_response = requests.post(f"{BASE_URL}/auth/login", json=login_data)
        if login_response.status_code == 200:
            login_result = login_response.json()
            if login_result.get("success"):
                user_id = login_result["data"]["user"]["id"]
                print(f"登录成功，用户ID: {user_id}")
                return user_id

        return None
    except Exception as e:
        print(f"创建用户出错: {e}")
        return None

def test_file_upload(user_id):
    """测试文件上传"""
    test_content = "Hello World! 测试文件上传内容"

    try:
        files = {
            "file": ("test.txt", test_content.encode("utf-8"), "text/plain")
        }
        data = {
            "user_id": user_id,
            "description": "测试文件上传",
            "tags": "test,upload,api",
            "is_public": "false"
        }

        response = requests.post(
            f"{BASE_URL}/files/upload",
            files=files,
            data=data
        )

        print(f"上传状态码: {response.status_code}")
        print(f"上传响应: {response.text}")

        if response.status_code == 201:
            result = response.json()
            if result.get("success"):
                file_info = result["data"]["file"]
                print(f"上传成功! 文件ID: {file_info['id']}")
                print(f"文件名: {file_info['original_filename']}")
                print(f"文件大小: {file_info['file_size']} bytes")
                return file_info['id']

        return None
    except Exception as e:
        print(f"上传出错: {e}")
        return None

def test_file_list(user_id):
    """测试获取文件列表"""
    try:
        data = {
            "user_id": user_id,
            "page": 1,
            "size": 20
        }

        response = requests.post(
            f"{BASE_URL}/files/list",
            json=data
        )

        print(f"列表状态码: {response.status_code}")

        if response.status_code == 200:
            result = response.json()
            if result.get("success"):
                files = result["data"]["files"]
                pagination = result["data"]["pagination"]
                print(f"文件数量: {len(files)}")
                print(f"总数: {pagination['total']}")
                for f in files:
                    print(f"  - {f['original_filename']} ({f['file_size']} bytes)")
                    print(f"    ID: {f['id']}, 创建时间: {f['created_at']}")

    except Exception as e:
        print(f"获取列表出错: {e}")

def test_file_info(user_id, file_id):
    """测试获取文件信息"""
    try:
        data = {
            "user_id": user_id,
            "file_id": file_id
        }

        response = requests.post(
            f"{BASE_URL}/files/info",
            json=data
        )

        print(f"文件信息状态码: {response.status_code}")

        if response.status_code == 200:
            result = response.json()
            if result.get("success"):
                info = result["data"]
                print(f"文件信息:")
                print(f"  文件名: {info['original_filename']}")
                print(f"  大小: {info['file_size']} bytes")
                print(f"  MIME类型: {info['mime_type']}")
                print(f"  是否图片: {info['is_image']}")
                print(f"  是否文档: {info['is_document']}")
                print(f"  文件扩展名: {info['file_extension']}")
                print(f"  格式化大小: {info['size_formatted']}")

    except Exception as e:
        print(f"获取文件信息出错: {e}")

def test_storage_info(user_id):
    """测试存储信息"""
    try:
        data = {
            "user_id": user_id
        }

        response = requests.post(
            f"{BASE_URL}/files/storage/info",
            json=data
        )

        print(f"存储信息状态码: {response.status_code}")

        if response.status_code == 200:
            result = response.json()
            if result.get("success"):
                info = result["data"]
                print(f"存储信息:")
                print(f"  总配额: {info['total_quota']} bytes")
                print(f"  已使用: {info['used_space']} bytes")
                print(f"  可用空间: {info['available_space']} bytes")
                print(f"  使用百分比: {info['usage_percentage']:.2f}%")
                print(f"  文件数量: {info['file_count']}")

    except Exception as e:
        print(f"获取存储信息出错: {e}")

def test_file_update(user_id, file_id):
    """测试更新文件信息"""
    try:
        data = {
            "user_id": user_id,
            "file_id": file_id
        }

        update_data = {
            "description": "更新后的文件描述",
            "tags": "updated,test",
            "is_public": True
        }

        response = requests.post(
            f"{BASE_URL}/files/update",
            json=data,
            params=update_data
        )

        print(f"更新文件状态码: {response.status_code}")

        if response.status_code == 200:
            result = response.json()
            if result.get("success"):
                file_info = result["data"]["file"]
                print(f"文件更新成功:")
                print(f"  描述: {file_info['description']}")
                print(f"  标签: {file_info['tags']}")
                print(f"  是否公开: {file_info['is_public']}")

    except Exception as e:
        print(f"更新文件出错: {e}")

def test_file_download(user_id, file_id):
    """测试文件下载"""
    try:
        data = {
            "user_id": user_id,
            "file_id": file_id
        }

        response = requests.post(
            f"{BASE_URL}/files/download",
            json=data
        )

        print(f"下载状态码: {response.status_code}")

        if response.status_code == 200:
            print(f"下载成功! 内容长度: {len(response.content)} bytes")
            print(f"下载内容: {response.text[:100]}...")  # 显示前100个字符
        else:
            print(f"下载失败: {response.text}")

    except Exception as e:
        print(f"下载出错: {e}")

def test_file_delete(user_id, file_id):
    """测试删除文件"""
    try:
        data = {
            "user_id": user_id,
            "file_id": file_id
        }

        response = requests.post(
            f"{BASE_URL}/files/delete",
            json=data
        )

        print(f"删除状态码: {response.status_code}")

        if response.status_code == 200:
            result = response.json()
            if result.get("success"):
                print("文件删除成功")
            else:
                print(f"删除失败: {result}")
        else:
            print(f"删除请求失败: {response.text}")

    except Exception as e:
        print(f"删除文件出错: {e}")

if __name__ == "__main__":
    print("开始测试POST文件API...")

    # 1. 创建测试用户
    user_id = create_test_user()
    if not user_id:
        print("无法创建或获取用户，退出测试")
        exit(1)

    # 2. 上传文件
    print("\n=== 测试文件上传 ===")
    file_id = test_file_upload(user_id)
    if not file_id:
        print("文件上传失败，继续其他测试")

    # 3. 获取文件列表
    print("\n=== 测试文件列表 ===")
    test_file_list(user_id)

    # 4. 获取存储信息
    print("\n=== 测试存储信息 ===")
    test_storage_info(user_id)

    # 5. 获取文件信息
    if file_id:
        print("\n=== 测试文件信息 ===")
        test_file_info(user_id, file_id)

        # 6. 更新文件信息
        print("\n=== 测试文件更新 ===")
        test_file_update(user_id, file_id)

        # 7. 下载文件
        print("\n=== 测试文件下载 ===")
        test_file_download(user_id, file_id)

        # 8. 删除文件
        print("\n=== 测试文件删除 ===")
        test_file_delete(user_id, file_id)

    print("\n测试完成!")