"""修复 user 表中因连接未使用 utf8mb4 而变成 ?? 的姓名（与 sql/init_db.sql 种子一致）。"""
import os
import sys

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if ROOT not in sys.path:
    sys.path.insert(0, ROOT)

from app import create_app
from app.config import mysql_uri_with_utf8mb4
from app.models import User, db

# user_id -> (first_name 名字, last_name 姓氏)
NAMES = {
    1: ('系统', '管理员'),
    2: ('开发', '人员'),
    3: ('演示', '用户'),
}


def main() -> None:
    uri = os.environ.get('SQLALCHEMY_DATABASE_URI')
    if uri:
        os.environ['SQLALCHEMY_DATABASE_URI'] = mysql_uri_with_utf8mb4(uri)

    app = create_app()
    with app.app_context():
        updated = 0
        for user_id, (first_name, last_name) in NAMES.items():
            user = db.session.get(User, user_id)
            if not user:
                continue
            if user.first_name == first_name and user.last_name == last_name:
                continue
            user.first_name = first_name
            user.last_name = last_name
            updated += 1
            print(f'user_id={user_id} ({user.username}): {first_name!r} / {last_name!r}')
        if updated:
            db.session.commit()
            print(f'已更新 {updated} 条用户姓名。')
        else:
            print('无需更新（姓名已正确）。')


if __name__ == '__main__':
    main()
