"""
数据库迁移脚本：为申请表添加拒绝次数控制字段
"""
import sqlite3
import os

db_path = 'instance/database.db'

if not os.path.exists(db_path):
    print(f"错误：找不到数据库文件 {db_path}")
    exit(1)

conn = sqlite3.connect(db_path)
cursor = conn.cursor()

print("开始数据库迁移...")

# 检查并更新 teacher_application 表
print("\n检查 teacher_application 表...")
cursor.execute("PRAGMA table_info(teacher_application)")
columns = [row[1] for row in cursor.fetchall()]
print(f"现有列: {columns}")

if 'rejection_count' not in columns:
    print("添加 rejection_count 字段...")
    cursor.execute("ALTER TABLE teacher_application ADD COLUMN rejection_count INTEGER DEFAULT 0")
    print("[OK] 已添加 rejection_count 字段")
else:
    print("[OK] rejection_count 字段已存在")

if 'last_rejected_at' not in columns:
    print("添加 last_rejected_at 字段...")
    cursor.execute("ALTER TABLE teacher_application ADD COLUMN last_rejected_at DATETIME")
    print("[OK] 已添加 last_rejected_at 字段")
else:
    print("[OK] last_rejected_at 字段已存在")

# 检查并更新 contest_application 表
print("\n检查 contest_application 表...")
cursor.execute("PRAGMA table_info(contest_application)")
columns = [row[1] for row in cursor.fetchall()]
print(f"现有列: {columns}")

if 'rejection_count' not in columns:
    print("添加 rejection_count 字段...")
    cursor.execute("ALTER TABLE contest_application ADD COLUMN rejection_count INTEGER DEFAULT 0")
    print("[OK] 已添加 rejection_count 字段")
else:
    print("[OK] rejection_count 字段已存在")

if 'last_rejected_at' not in columns:
    print("添加 last_rejected_at 字段...")
    cursor.execute("ALTER TABLE contest_application ADD COLUMN last_rejected_at DATETIME")
    print("[OK] 已添加 last_rejected_at 字段")
else:
    print("[OK] last_rejected_at 字段已存在")

conn.commit()
conn.close()

print("\n[SUCCESS] 数据库迁移完成！")
print("现在可以正常使用申请功能了。")
