"""
批量修正 docs/database/ 下 BD_Manual 文档中的过时路径引用。
- 迁移脚本路径 → 标注为已归档
- DDL 位置 → 更新为新的 docs/database/ddl/ 路径
- 旧 schema 文件引用 → 更新

用法：cd C:\\NeoZQYY && python scripts/ops/_fix_bd_manual_refs.py
"""
import re
from pathlib import Path

ROOT = Path(__file__).resolve().parent.parent.parent

# 需要处理的目录
DIRS = [
    ROOT / "docs" / "database",
    ROOT / "apps" / "etl" / "connectors" / "feiqiu" / "docs" / "database",
]

# 路径替换规则
REPLACEMENTS = [
    # 迁移脚本路径 → 标注已归档
    (r'`db/etl_feiqiu/migrations/([^`]+)`',
     r'`db/_archived/ddl_baseline_2026-02-22/db/etl_feiqiu/migrations/\1`（已归档）'),
    (r'`db/zqyy_app/migrations/([^`]+)`',
     r'`db/_archived/ddl_baseline_2026-02-22/db/zqyy_app/migrations/\1`（已归档）'),

    # DDL 位置引用旧 schema 文件
    (r'`db/etl_feiqiu/schemas/meta\.sql`', '`docs/database/ddl/etl_feiqiu__meta.sql`'),
    (r'`db/etl_feiqiu/schemas/ods\.sql`', '`docs/database/ddl/etl_feiqiu__ods.sql`'),
    (r'`db/etl_feiqiu/schemas/dwd\.sql`', '`docs/database/ddl/etl_feiqiu__dwd.sql`'),
    (r'`db/etl_feiqiu/schemas/core\.sql`', '`docs/database/ddl/etl_feiqiu__core.sql`'),
    (r'`db/etl_feiqiu/schemas/dws\.sql`', '`docs/database/ddl/etl_feiqiu__dws.sql`'),
    (r'`db/etl_feiqiu/schemas/app\.sql`', '`docs/database/ddl/etl_feiqiu__app.sql`'),
    (r'`db/zqyy_app/schemas/init\.sql`', '`docs/database/ddl/zqyy_app__public.sql`'),

    # 旧 schema 文件名（不带路径前缀）
    (r'`database/schema_ODS_doc\.sql`', '`docs/database/ddl/etl_feiqiu__ods.sql`'),
    (r'`database/schema_dwd_doc\.sql`', '`docs/database/ddl/etl_feiqiu__dwd.sql`'),
    (r'`database/schema_dws\.sql`', '`docs/database/ddl/etl_feiqiu__dws.sql`'),
    (r'`database/schema_etl_admin\.sql`', '`docs/database/ddl/etl_feiqiu__meta.sql`'),

    # DDL 位置行
    (r'DDL 位置：`db/etl_feiqiu/schemas/dws\.sql`',
     'DDL 位置：`docs/database/ddl/etl_feiqiu__dws.sql`'),
]


def process_file(filepath):
    """处理单个文件，返回修改数量。"""
    text = filepath.read_text(encoding="utf-8")
    original = text
    changes = 0

    for pattern, replacement in REPLACEMENTS:
        new_text, n = re.subn(pattern, replacement, text)
        if n > 0:
            changes += n
            text = new_text

    if changes > 0:
        filepath.write_text(text, encoding="utf-8")

    return changes


def main():
    total_files = 0
    total_changes = 0

    for d in DIRS:
        if not d.exists():
            continue
        for md_file in sorted(d.rglob("*.md")):
            # 跳过 _archived 目录
            if "_archived" in str(md_file):
                continue
            changes = process_file(md_file)
            if changes > 0:
                rel = md_file.relative_to(ROOT)
                print(f"  ✅ {rel} ({changes} 处替换)")
                total_files += 1
                total_changes += changes

    print(f"\n✅ 完成：修改 {total_files} 个文件，共 {total_changes} 处替换")


if __name__ == "__main__":
    main()
