#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
恢复备份数据
检查备份文件中是否有红豆门诊的处理数据
"""

import os
import pickle
import shutil
from datetime import datetime

def check_backup_data():
    """检查备份文件中的数据"""
    print("🔍 检查备份文件中的红豆门诊数据...")
    
    progress_dir = "progress_saves"
    
    # 查找最新的备份文件
    backup_files = []
    for file_name in os.listdir(progress_dir):
        if file_name.startswith('session_20250805_232912_backup_'):
            file_path = os.path.join(progress_dir, file_name)
            backup_files.append((file_name, file_path, os.path.getmtime(file_path)))
    
    if not backup_files:
        print("❌ 未找到备份文件")
        return
    
    # 使用最新的备份文件
    backup_files.sort(key=lambda x: x[2], reverse=True)
    latest_backup = backup_files[0]
    backup_file = latest_backup[1]
    
    print(f"📁 使用备份文件: {latest_backup[0]}")
    
    try:
        with open(backup_file, 'rb') as f:
            backup_data = pickle.load(f)
        
        print("\n📊 备份文件信息:")
        print(f"   - 当前诊所: {backup_data.get('current_clinic', '未知')}")
        print(f"   - 当前患者索引: {backup_data.get('current_patient_index', 0)}")
        print(f"   - 保存时间: {backup_data.get('save_timestamp', '未知')}")
        
        # 检查当前诊所的处理数据
        current_callbacks = backup_data.get('current_clinic_callbacks', [])
        print(f"\n📊 当前诊所处理数据:")
        if current_callbacks:
            success_count = len([cb for cb in current_callbacks if cb.get('callback_type') == 'success'])
            error_count = len([cb for cb in current_callbacks if cb.get('callback_type') == 'error'])
            print(f"   - 总处理: {len(current_callbacks)} 个患者")
            print(f"   - ✅ 成功: {success_count} 个")
            print(f"   - ❌ 失败: {error_count} 个")
            
            # 显示一些处理的患者信息
            if len(current_callbacks) > 0:
                print(f"\n📋 处理的患者样本:")
                sample_size = min(5, len(current_callbacks))
                for i in range(sample_size):
                    cb = current_callbacks[i]
                    status = "✅" if cb.get('callback_type') == 'success' else "❌"
                    print(f"   {i+1}. {cb.get('patient_name', '未知')} ({cb.get('patient_id', '未知')}) {status}")
                
                if len(current_callbacks) > 5:
                    print(f"   ... 还有 {len(current_callbacks) - 5} 个患者")
        else:
            print("   - 无处理数据")
        
        # 检查是否需要恢复
        if backup_data.get('current_clinic') == '红豆门诊' and current_callbacks:
            print(f"\n🎯 发现红豆门诊数据！")
            print(f"   - 诊所: 红豆门诊")
            print(f"   - 处理进度: {len(current_callbacks)} 个患者")
            print(f"   - 当前索引: {backup_data.get('current_patient_index', 0)}")
            
            restore = input("\n是否恢复这些数据？(Y/n): ").strip().lower()
            if restore in ['', 'y', 'yes']:
                restore_data(backup_file)
            else:
                print("取消恢复")
        else:
            print(f"\n⚠️ 备份文件中当前诊所是: {backup_data.get('current_clinic')}")
            print("   可能红豆门诊数据在其他地方，让我检查all_results...")
            
            all_results = backup_data.get('all_results', {})
            if '红豆门诊' in all_results:
                red_data = all_results['红豆门诊']
                print(f"   🎯 在all_results中找到红豆门诊数据: {len(red_data)} 个患者")
                
                restore = input("\n是否恢复all_results中的红豆门诊数据？(Y/n): ").strip().lower()
                if restore in ['', 'y', 'yes']:
                    restore_all_results_data(backup_file)
                else:
                    print("取消恢复")
            else:
                print("   ❌ 在all_results中也未找到红豆门诊数据")
        
    except Exception as e:
        print(f"❌ 读取备份文件失败: {e}")
        import traceback
        traceback.print_exc()

def restore_data(backup_file):
    """恢复备份数据"""
    print("\n🔄 恢复备份数据...")
    
    try:
        # 读取备份数据
        with open(backup_file, 'rb') as f:
            backup_data = pickle.load(f)
        
        # 恢复当前会话文件
        session_file = "progress_saves/session_20250805_232912.pkl"
        
        # 创建恢复前的备份
        restore_backup = f"progress_saves/before_restore_{datetime.now().strftime('%Y%m%d_%H%M%S')}.pkl"
        shutil.copy2(session_file, restore_backup)
        
        # 恢复数据
        with open(session_file, 'wb') as f:
            pickle.dump(backup_data, f)
        
        print("✅ 数据恢复成功！")
        print(f"✅ 已创建恢复前备份: {os.path.basename(restore_backup)}")
        
        # 验证恢复结果
        with open(session_file, 'rb') as f:
            restored_data = pickle.load(f)
        
        print(f"\n📊 恢复后状态:")
        print(f"   - 当前诊所: {restored_data.get('current_clinic', '未知')}")
        print(f"   - 当前患者索引: {restored_data.get('current_patient_index', 0)}")
        current_callbacks = restored_data.get('current_clinic_callbacks', [])
        if current_callbacks:
            success_count = len([cb for cb in current_callbacks if cb.get('callback_type') == 'success'])
            print(f"   - 当前诊所处理: {len(current_callbacks)} 个患者 (✅{success_count})")
        
    except Exception as e:
        print(f"❌ 恢复失败: {e}")
        import traceback
        traceback.print_exc()

def restore_all_results_data(backup_file):
    """恢复all_results中的红豆门诊数据"""
    print("\n🔄 恢复all_results中的红豆门诊数据...")
    
    try:
        # 读取备份数据
        with open(backup_file, 'rb') as f:
            backup_data = pickle.load(f)
        
        # 读取当前会话数据
        session_file = "progress_saves/session_20250805_232912.pkl"
        with open(session_file, 'rb') as f:
            current_data = pickle.load(f)
        
        # 恢复红豆门诊数据到all_results
        if 'all_results' not in current_data:
            current_data['all_results'] = {}
        
        red_data = backup_data.get('all_results', {}).get('红豆门诊', [])
        current_data['all_results']['红豆门诊'] = red_data
        
        # 将红豆门诊添加到已完成列表
        if '红豆门诊' not in current_data.get('completed_clinics', []):
            current_data.setdefault('completed_clinics', []).append('红豆门诊')
        
        # 如果当前诊所是红豆门诊，切换到下一个诊所
        if current_data.get('current_clinic') == '红豆门诊':
            selected_clinics = current_data.get('generation_config', {}).get('selected_clinics', [])
            completed_clinics = current_data.get('completed_clinics', [])
            remaining_clinics = [c for c in selected_clinics if c not in completed_clinics]
            
            if remaining_clinics:
                current_data['current_clinic'] = remaining_clinics[0]
                current_data['current_patient_index'] = 0
                current_data['current_clinic_callbacks'] = []
                print(f"   ✅ 切换到下一个诊所: {remaining_clinics[0]}")
        
        # 更新时间戳
        current_data['save_timestamp'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        current_data['last_save_time'] = datetime.now()
        
        # 保存恢复的数据
        with open(session_file, 'wb') as f:
            pickle.dump(current_data, f)
        
        print("✅ 红豆门诊数据恢复成功！")
        print(f"✅ 恢复 {len(red_data)} 个患者的处理结果")
        print(f"✅ 红豆门诊已标记为完成")
        
    except Exception as e:
        print(f"❌ 恢复失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    check_backup_data() 