# -*- coding: utf-8 -*-
"""批量替换运行时代码中残留的旧 schema 引用。"""
import os

ROOT = r"C:\NeoZQYY"

import glob

# 自动扫描所有运行时 Python 文件（排除 tests 目录）
SCAN_DIRS = [
    "apps/etl/connectors/feiqiu",
    "apps/backend/app",
    "gui",
]
TARGETS = []
for d in SCAN_DIRS:
    full = os.path.join(ROOT, d)
    for py in glob.glob(os.path.join(full, "**", "*.py"), recursive=True):
        rel = os.path.relpath(py, ROOT).replace("\\", "/")
        # 排除测试目录和 hypothesis 缓存
        if "/tests/" not in rel and "/.hypothesis/" not in rel:
            TARGETS.append(rel)

REPLACEMENTS = {
    "billiards_ods.": "ods.",
    "billiards_dwd.": "dwd.",
    "billiards_dws.": "dws.",
    "'billiards_ods'": "'ods'",
    "'billiards_dwd'": "'dwd'",
    "'billiards_dws'": "'dws'",
    '"billiards_ods"': '"ods"',
    '"billiards_dwd"': '"dwd"',
    '"billiards_dws"': '"dws"',
    # 注释/文档/CLI 中不带点号的引用（空格或行尾结尾）
    "billiards_ods ": "ods ",
    "billiards_dwd ": "dwd ",
    "billiards_dws ": "dws ",
    "billiards_ods\n": "ods\n",
    "billiards_dwd\n": "dwd\n",
    "billiards_dws\n": "dws\n",
    # 括号包裹
    "(billiards_ods)": "(ods)",
    "(billiards_dwd)": "(dwd)",
    "(billiards_dws)": "(dws)",
    # 反引号包裹
    "`billiards_ods`": "`ods`",
    "`billiards_dwd`": "`dwd`",
    "`billiards_dws`": "`dws`",
}

total = 0
for rel in TARGETS:
    fp = os.path.join(ROOT, rel)
    if not os.path.exists(fp):
        print(f"SKIP (not found): {rel}")
        continue
    with open(fp, "r", encoding="utf-8") as f:
        content = f.read()
    new_content = content
    count = 0
    for old, new in REPLACEMENTS.items():
        c = new_content.count(old)
        if c > 0:
            new_content = new_content.replace(old, new)
            count += c
    if count > 0:
        with open(fp, "w", encoding="utf-8") as f:
            f.write(new_content)
        print(f"FIXED ({count} replacements): {rel}")
        total += count
    else:
        print(f"CLEAN: {rel}")

print(f"\nTotal replacements: {total}")
