import os
import django

# 设置Django环境
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'role_based_system.settings')
django.setup()

from user_management.models import GmailCredential

# 清除特定凭证
def fix_specific_credential(credential_id):
    try:
        cred = GmailCredential.objects.get(id=credential_id)
        cred.credentials = None
        cred.needs_reauth = True
        cred.save()
        print(f'已清除ID为{cred.id}的凭证，邮箱: {cred.gmail_email}，并标记为需要重新授权')
        return True
    except GmailCredential.DoesNotExist:
        print(f'找不到ID为{credential_id}的凭证')
        return False
    except Exception as e:
        print(f'处理凭证{credential_id}时出错: {str(e)}')
        return False

# 清除所有可能已损坏的凭证
def fix_all_credentials():
    credentials = GmailCredential.objects.all()
    fixed_count = 0
    
    for cred in credentials:
        if cred.credentials:  # 只处理有凭证数据的记录
            try:
                # 直接清除凭证并标记需要重新认证
                cred.credentials = None
                cred.needs_reauth = True
                cred.save()
                print(f'已清除ID为{cred.id}的凭证，邮箱: {cred.gmail_email}')
                fixed_count += 1
            except Exception as e:
                print(f'处理凭证{cred.id}时出错: {str(e)}')
    
    print(f'共清除了{fixed_count}个凭证')

if __name__ == '__main__':
    # 修复特定的凭证
    fix_specific_credential('936c37a7-c6e5-454a-aaef-7c66b1230507')
    
    # 或者修复所有凭证
    # fix_all_credentials() 