#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""整理后遗症修复：把被移动目录的引用路径改到新位置。
处理 6 类真断链（其余匹配均为关键词表/JSON 标签/下载文件名，非路径，不动）。
"""
import os, re

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.chdir(ROOT)

# ① 点对点替换（活跃脚本）
POINT = {
    '脚本/build_product_mapping.py': [
        ("os.path.join(WORK, '数据分析')", "os.path.join(WORK, '经营分析', '数据分析')")],
    '脚本/build_product_catalogs.py': [
        ("os.path.join(BASE, '产品/促销素材')", "os.path.join(BASE, '产品与市场', '产品', '促销素材')")],
    '脚本/html_lint.py': [
        ("'会话存档'", "'行政与商务/会话存档'"),
        ("'培训资料'", "'培训与上手/培训资料'")],
    '.q3scratch/verify_ownerfix2.py': [
        ("{W}/_bak_ownerfix2_20261006_212914", "{W}/归档/_版本备份/_bak_ownerfix2_20261006_212914")],
}

# ② 整目录扫描替换（移动目录内的一次性脚本）
GLOB_RULES = [
    ('培训与上手/培训', [
        (r'/Hermes输出-工作类/培训/', '/Hermes输出-工作类/培训与上手/培训/'),
        (r"os\.path\.join\(\s*W\s*,\s*'培训'", "os.path.join(W, '培训与上手', '培训'"),
        (r'os\.path\.join\(\s*W\s*,\s*"培训"', 'os.path.join(W, "培训与上手", "培训"'),
    ]),
    ('培训与上手/刘子研上手包', [
        (r'/Hermes输出-工作类/刘子研上手包', '/Hermes输出-工作类/培训与上手/刘子研上手包'),
        (r"\{BASE\}/刘子研上手包", "{BASE}/培训与上手/刘子研上手包"),
    ]),
]

n_files = n_edits = 0
print('═══ ① 点对点修复 ═══')
for fp, subs in POINT.items():
    if not os.path.isfile(fp):
        print('  ⚠️ 文件不存在：%s' % fp); continue
    t = open(fp, encoding='utf-8').read(); orig = t
    for old, new in subs:
        c = t.count(old)
        if c:
            t = t.replace(old, new); n_edits += c
            print('  ✅ %-38s %-34s ×%d' % (fp, old[:34], c))
        else:
            print('  ⚠️ %-38s 未命中：%s' % (fp, old[:34]))
    if t != orig:
        open(fp, 'w', encoding='utf-8').write(t); n_files += 1

print('\n═══ ② 移动目录内一次性脚本 ═══')
for d, rules in GLOB_RULES:
    cnt = 0
    for dp, ds, fs in os.walk(d):
        if '__pycache__' in dp:
            continue
        for f in fs:
            if not f.endswith(('.py', '.sh', '.js')):
                continue
            fp = os.path.join(dp, f)
            t = open(fp, encoding='utf-8', errors='ignore').read(); orig = t
            for pat, rep in rules:
                t2 = re.sub(pat, rep, t)
                if t2 != t:
                    cnt += len(re.findall(pat, t)); t = t2
            if t != orig:
                open(fp, 'w', encoding='utf-8').write(t); n_files += 1
    print('  ✅ %-24s 修 %d 处' % (d, cnt)); n_edits += cnt

print('\n合计：改 %d 个文件 / %d 处引用' % (n_files, n_edits))
