#!/usr/bin/env python3
"""
调试文件下载接口的脚本
"""

import requests
import mysql.connector
import os
import json

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

def debug_download_issue():
    """调试下载接口问题"""

    print("=== 调试文件下载接口 ===")

    # 检查数据库中的文件信息
    try:
        conn = mysql.connector.connect(
            host="101.126.85.76",
            user="mytest_db",
            password="mytest_db",
            database="mytest_db"
        )
        cursor = conn.cursor()

        # 查询所有文件
        cursor.execute("""
            SELECT id, user_id, original_filename, filename, file_path, file_size,
                   file_hash, mime_type, created_at
            FROM files
            ORDER BY id
        """)
        files = cursor.fetchall()

        print("数据库中的文件记录:")
        for file in files:
            (id, user_id, original_filename, filename, file_path,
             file_size, file_hash, mime_type, created_at) = file
            print(f"ID: {id}, 用户ID: {user_id}, 文件名: {original_filename}")
            print(f"  存储路径: {file_path}")
            print(f"  文件大小: {file_size} bytes")
            print(f"  创建时间: {created_at}")
            print("-" * 50)

        cursor.close()
        conn.close()

    except Exception as e:
        print(f"数据库查询出错: {e}")
        return

    # 测试特定文件下载
    test_cases = [
        {"user_id": 3, "file_id": 2, "description": "用户3下载文件2(axurerp-48.png)"},
        {"user_id": 3, "file_id": 3, "description": "用户3下载文件3(axurerp-128.png)"},
        {"user_id": 8, "file_id": 4, "description": "用户8下载文件4(hash_demo.txt)"},
        {"user_id": 3, "file_id": 4, "description": "用户3下载文件4(权限测试)"},
        {"user_id": 1, "file_id": 2, "description": "用户1下载文件2(不存在用户)"},
        {"user_id": 3, "file_id": 999, "description": "用户3下载文件999(不存在文件)"},
    ]

    for test_case in test_cases:
        user_id = test_case["user_id"]
        file_id = test_case["file_id"]
        description = test_case["description"]

        print(f"\n=== 测试: {description} ===")
        print(f"入参: user_id={user_id}, file_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"HTTP状态码: {response.status_code}")

            if response.status_code == 200:
                # 下载成功
                content_length = len(response.content)
                print(f"下载成功! 文件大小: {content_length} bytes")

                # 保存下载的文件用于检查
                save_filename = f"downloaded_user{user_id}_file{file_id}"
                if content_length > 0:
                    with open(save_filename, 'wb') as f:
                        f.write(response.content)
                    print(f"文件已保存为: {save_filename}")
                else:
                    print("警告: 下载的文件为空")

                # 显示内容预览
                try:
                    if response.headers.get('content-type', '').startswith('text/'):
                        text_content = response.content.decode('utf-8')
                        preview = text_content[:100] + "..." if len(text_content) > 100 else text_content
                        print(f"内容预览: {preview}")
                    else:
                        print("二进制文件，无法预览内容")
                except:
                    print("无法预览文件内容")

            else:
                # 下载失败
                print(f"下载失败!")
                print(f"响应内容: {response.text}")

                # 尝试解析JSON错误信息
                try:
                    error_data = response.json()
                    print(f"错误详情: {json.dumps(error_data, indent=2, ensure_ascii=False)}")
                except:
                    print("无法解析错误响应")

        except Exception as e:
            print(f"请求出错: {e}")

def check_file_access_permission():
    """检查文件访问权限"""

    print("\n=== 检查文件访问权限 ===")

    # 检查uploads目录权限
    uploads_dir = "uploads"
    if os.path.exists(uploads_dir):
        print(f"uploads目录存在: {os.path.abspath(uploads_dir)}")

        # 检查目录权限
        try:
            test_file = os.path.join(uploads_dir, "test_permission.txt")
            with open(test_file, 'w') as f:
                f.write("test")

            if os.path.exists(test_file):
                os.remove(test_file)
                print("uploads目录读写权限正常")
            else:
                print("uploads目录权限异常")
        except Exception as e:
            print(f"无法在uploads目录写入文件: {e}")
    else:
        print("uploads目录不存在")

    # 检查数据库文件记录与实际文件的对应关系
    try:
        conn = mysql.connector.connect(
            host="101.126.85.76",
            user="mytest_db",
            password="mytest_db",
            database="mytest_db"
        )
        cursor = conn.cursor()

        cursor.execute("SELECT id, user_id, filename, file_path FROM files ORDER BY id")
        files = cursor.fetchall()

        print("\n文件记录与实际文件对应关系:")
        for (id, user_id, filename, file_path) in files:
            full_path = os.path.join("uploads", filename)
            exists = os.path.exists(full_path)
            if exists:
                size = os.path.getsize(full_path)
                print(f"ID {id}: 文件存在 ({size} bytes)")
            else:
                print(f"ID {id}: 文件不存在 - {full_path}")

        cursor.close()
        conn.close()

    except Exception as e:
        print(f"检查文件对应关系出错: {e}")

def test_download_with_curl():
    """使用curl测试下载接口"""

    print("\n=== 使用curl测试下载接口 ===")

    test_cases = [
        {"user_id": 3, "file_id": 2},
        {"user_id": 3, "file_id": 3},
    ]

    for test_case in test_cases:
        user_id = test_case["user_id"]
        file_id = test_case["file_id"]

        print(f"\n测试 curl - 用户ID: {user_id}, 文件ID: {file_id}")

        curl_command = f'''curl -X POST "{BASE_URL}/files/download" \\
-H "Content-Type: application/json" \\
-d '{{"user_id": {user_id}, "file_id": {file_id}}}' \\
-v'''

        print("命令:")
        print(curl_command)
        print("(请在终端中手动执行此命令)")

if __name__ == "__main__":
    debug_download_issue()
    check_file_access_permission()
    test_download_with_curl()

    print("\n=== 调试总结 ===")
    print("如果下载失败，可能的原因:")
    print("1. 文件不存在或已被删除")
    print("2. 用户ID与文件不匹配")
    print("3. uploads目录权限问题")
    print("4. 实际文件大小为0字节")
    print("5. 下载接口实现逻辑问题")