import os
import re

ROOT_DIR = r"d:\ALONGF\Django"
EXCLUDE_DIRS = {"migrations", "__pycache__", ".git", "node_modules", ".venv", "idea"}
EXCLUDE_FILES = {"migrate_to_gvsdsdk_user.py", "rp.py", "refactor_replace.py"}

SAFE_REPLACEMENTS = {
    "shoujihao_renzheng": "PhoneVerified",
    "last_login_time": "UserLastLoginDate",
    "openid": "OpenID",
    "user_type": "UserType",
    "dashou_profile": "DashouProfile",
    "shop_profile": "ShopProfile",
    "guanshi_profile": "GuanshiProfile",
    "boss_profile": "BossProfile",
    "admin_profile": "AdminProfile",
    "kefu_profile": "KefuProfile",
    "zuzhang_profile": "ZuzhangProfile",
    "shenheguan_profile": "ShenheguanProfile",
    "has_role": "HasRole",
}

UNSAFE_REPLACEMENTS = {
    "yonghuid": "UserUID",
    "avatar": "Avatar",
    "phone": "Phone",
    "ip": "IP",
    "CreateTime": "UserCreateTime",
    "zhifu": "PaymentQRCode",
    "skzhanghao": "PaymentAccount",
}

NON_USER_VARS = {
    "record", "tixian_record", "tixian", "audit",
    "item", "items",
    "shangjia", "product", "guanshi", "zuzhang",
    "bk", "ch", "sg", "p", "m",
    "huiyuan", "huiyuan_obj", "shangbin_obj", "shangpin_obj",
    "moban", "link", "dingdan_obj",
    "jl", "rej", "dianpu", "shop",
    "r", "rec", "chufa", "auto_record",
    "um", "hg", "xjl", "Dingdan",
    "obj", "tixian_obj",
    "sensitive_data", "self",
    "boss_profile", "dashou_profile", "guanshi_profile", "shop_profile",
    "kefu_profile", "admin_profile", "zuzhang_profile", "shenheguan_profile",
    "BossProfile", "DashouProfile", "GuanshiProfile", "ShopProfile",
    "KefuProfile", "AdminProfile", "ZuzhangProfile", "ShenheguanProfile",
    "shangjia_profile",
    "dingdan", "order", "tixian_shenhe",
}


def should_skip_dir(dirpath):
    for excl in EXCLUDE_DIRS:
        if excl in dirpath:
            return True
    return False


def process_content(content):
    # 1. Safe replacements: global .old -> .new
    for old, new in SAFE_REPLACEMENTS.items():
        pattern = r"\." + re.escape(old) + r"\b"
        content = re.sub(pattern, "." + new, content)

    # 2. Unsafe replacements: targeted, only on User instance variables
    for old, new in UNSAFE_REPLACEMENTS.items():
        def make_replacer(new_name):
            def replacer(m):
                var = m.group(1)
                if var in NON_USER_VARS:
                    return m.group(0)
                return var + "." + new_name
            return replacer
        pattern = r"(?<!\w)(\w+)\." + re.escape(old) + r"\b"
        content = re.sub(pattern, make_replacer(new), content)

    # 3. hasattr string replacements
    all_replacements = {**SAFE_REPLACEMENTS, **UNSAFE_REPLACEMENTS}
    for old, new in all_replacements.items():
        def make_hasattr_replacer(new_name, old_name):
            def replacer(m):
                var = m.group(1)
                if old_name in UNSAFE_REPLACEMENTS and var in NON_USER_VARS:
                    return m.group(0)
                return "hasattr(" + var + ", '" + new_name + "')"
            return replacer
        pattern = r"hasattr\((\w+),\s*['\"]" + re.escape(old) + r"['\"]\)"
        content = re.sub(pattern, make_hasattr_replacer(new, old), content)

    return content


def main():
    total_mod = 0
    for root, dirs, files in os.walk(ROOT_DIR):
        if should_skip_dir(root):
            continue
        for fname in files:
            if not fname.endswith(".py"):
                continue
            if fname in EXCLUDE_FILES:
                continue
            file_path = os.path.join(root, fname)
            try:
                with open(file_path, "r", encoding="utf-8") as f:
                    content = f.read()
                new_content = process_content(content)
                if new_content != content:
                    with open(file_path, "w", encoding="utf-8") as f:
                        f.write(new_content)
                    print("modified: " + file_path)
                    total_mod += 1
            except Exception as err:
                print("error " + file_path + ": " + str(err))
    print("\ndone, modified " + str(total_mod) + " files")


if __name__ == "__main__":
    main()
