#!/usr/bin/env python3
"""
逐步调试文件上传过程的每个步骤
"""

import requests
import io
import os

def debug_upload_step_by_step():
    """逐步调试上传过程"""

    print("=== 步骤1: 准备测试文件 ===")
    test_content = b"Debug upload content - step by step analysis"
    print(f"原始内容大小: {len(test_content)} bytes")
    print(f"原始内容: {test_content}")
    print()

    print("=== 步骤2: 创建模拟上传文件 ===")
    file_obj = io.BytesIO(test_content)
    file_obj.seek(0)
    print(f"BytesIO对象创建成功")
    print(f"当前位置: {file_obj.tell()}")
    print()

    print("=== 步骤3: 准备请求数据 ===")
    files = {
        'file': ('debug_step_test.txt', file_obj, 'text/plain')
    }
    data = {
        'user_id': 3,
        'description': 'Step by step debug test',
        'tags': 'debug,step',
        'is_public': 'false'
    }
    print("请求数据准备完成")
    print()

    print("=== 步骤4: 发送上传请求 ===")
    try:
        response = requests.post('http://localhost:8000/api/v1/files/upload', files=files, data=data)
        print(f"响应状态码: {response.status_code}")
        print(f"响应头: {dict(response.headers)}")

        if response.status_code == 201:
            result = response.json()
            print("=== 步骤5: 上传成功分析 ===")
            if result.get('success'):
                file_info = result['data']['file']
                file_id = file_info['id']
                filename = file_info['filename']
                db_size = file_info['file_size']

                print(f"数据库记录:")
                print(f"  文件ID: {file_id}")
                print(f"  存储文件名: {filename}")
                print(f"  数据库大小: {db_size} bytes")
                print(f"  预期大小: {len(test_content)} bytes")

                # 检查磁盘文件
                print("\n=== 步骤6: 磁盘文件分析 ===")
                file_path = os.path.join('uploads', filename)
                print(f"预期路径: {file_path}")

                if os.path.exists(file_path):
                    actual_size = os.path.getsize(file_path)
                    print(f"实际文件大小: {actual_size} bytes")

                    if actual_size == 0:
                        print("❌ 文件损坏: 大小为0")
                    elif actual_size == len(test_content):
                        print("✅ 文件完整")

                        # 验证内容
                        with open(file_path, 'rb') as f:
                            actual_content = f.read()

                        if actual_content == test_content:
                            print("✅ 内容完全匹配")
                        else:
                            print("❌ 内容不匹配")
                            print(f"预期: {test_content}")
                            print(f"实际: {actual_content}")
                    else:
                        print(f"⚠️ 大小不匹配: {actual_size} != {len(test_content)}")

                        # 读取部分内容检查
                        try:
                            with open(file_path, 'rb') as f:
                                actual_content = f.read(min(100, actual_size))
                            print(f"实际内容预览: {actual_content}")
                        except Exception as e:
                            print(f"无法读取文件内容: {e}")
                else:
                    print("❌ 文件不存在于磁盘")

                    # 检查目录
                    upload_dir = 'uploads'
                    if os.path.exists(upload_dir):
                        print(f"uploads目录存在")
                        files_in_dir = os.listdir(upload_dir)
                        print(f"目录中的文件: {files_in_dir}")
                    else:
                        print("uploads目录不存在")

            else:
                print("上传返回失败:", result)
        else:
            print("=== 步骤5: 上传失败分析 ===")
            print(f"HTTP状态码: {response.status_code}")
            print(f"响应内容: {response.text}")

            # 尝试解析错误
            try:
                error_data = response.json()
                print(f"错误详情: {error_data}")
            except:
                print("无法解析错误响应")

    except Exception as e:
        print(f"请求异常: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    debug_upload_step_by_step()