#!/usr/bin/env python3
"""
简化版文件存储检查脚本
"""

import mysql.connector
import os
import hashlib

def check_files_storage():
    """检查文件存储情况"""

    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 created_at DESC
        """)

        db_files = cursor.fetchall()
        print(f"数据库中的文件记录数: {len(db_files)}")
        print()

        print("=== 数据库中的文件记录 ===")
        for file in db_files:
            (id, user_id, original_filename, filename, file_path,
             file_size, file_hash, mime_type, created_at) = file

            print(f"ID: {id}")
            print(f"  原始文件名: {original_filename}")
            print(f"  存储文件名: {filename}")
            print(f"  文件大小: {file_size} bytes")
            print(f"  MIME类型: {mime_type}")
            print(f"  创建时间: {created_at}")
            print("-" * 40)

        # 检查实际文件存在情况
        print("\n=== 文件存在性检查 ===")
        existing_count = 0
        for file in db_files:
            (id, user_id, original_filename, filename, file_path,
             file_size, file_hash, mime_type, created_at) = file

            full_path = os.path.join("uploads", filename)
            if os.path.exists(full_path):
                existing_count += 1
                print(f"[存在] ID {id}: {original_filename}")
            else:
                print(f"[缺失] ID {id}: {original_filename}")

        print(f"\n实际存在的文件数: {existing_count}")
        print(f"缺失的文件数: {len(db_files) - existing_count}")

        # 检查uploads目录详情
        print("\n=== uploads目录详情 ===")
        uploads_dir = "uploads"
        if os.path.exists(uploads_dir):
            files = os.listdir(uploads_dir)
            print(f"uploads目录中的文件数: {len(files)}")

            for file in files:
                file_path = os.path.join(uploads_dir, file)
                file_size = os.path.getsize(file_path)
                print(f"文件: {file}, 大小: {file_size} bytes")
        else:
            print("uploads目录不存在")

    except Exception as e:
        print(f"检查出错: {e}")
    finally:
        if 'conn' in locals() and conn.is_connected():
            cursor.close()
            conn.close()

def check_file_integrity():
    """检查文件完整性"""

    print("\n=== 文件完整性检查 ===")

    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, filename, file_hash, file_size FROM files")
        db_files = cursor.fetchall()

        integrity_ok = True

        for (id, filename, expected_hash, expected_size) in db_files:
            full_path = os.path.join("uploads", filename)

            if os.path.exists(full_path):
                actual_size = os.path.getsize(full_path)
                if actual_size != expected_size:
                    print(f"ID {id}: 文件大小不匹配 (期望: {expected_size}, 实际: {actual_size})")
                    integrity_ok = False
                    continue

                try:
                    with open(full_path, 'rb') as f:
                        content = f.read()
                        actual_hash = hashlib.sha256(content).hexdigest()

                    if actual_hash != expected_hash:
                        print(f"ID {id}: 文件哈希不匹配")
                        print(f"  期望: {expected_hash}")
                        print(f"  实际: {actual_hash}")
                        integrity_ok = False
                    else:
                        print(f"ID {id}: 完整性检查通过")
                except Exception as e:
                    print(f"ID {id}: 无法计算哈希 - {e}")
                    integrity_ok = False
            else:
                print(f"ID {id}: 文件不存在")
                integrity_ok = False

        if integrity_ok:
            print("所有文件完整性检查通过!")
        else:
            print("发现文件完整性问题!")

    except Exception as e:
        print(f"完整性检查出错: {e}")
    finally:
        if 'conn' in locals() and conn.is_connected():
            cursor.close()
            conn.close()

if __name__ == "__main__":
    check_files_storage()
    check_file_integrity()

    print("\n=== 文件存储架构总结 ===")
    print("1. 数据库(files表): 存储文件元数据")
    print("   - 文件ID、用户ID、原始文件名")
    print("   - 存储文件名(UUID格式)")
    print("   - 文件大小、MIME类型")
    print("   - SHA-256哈希值")
    print("   - 创建时间等")
    print()
    print("2. 文件系统(uploads目录): 存储实际文件")
    print("   - 文件使用UUID命名确保唯一性")
    print("   - 文件内容与数据库记录一一对应")
    print("   - 通过file_hash验证完整性")
    print()
    print("3. 回答您的问题:")
    print("   是的，数据库中存储的是文件元数据，")
    print("   实际文件内容存储在服务器的uploads目录中。")
    print("   两者通过file_hash保持关联和完整性验证。")