# -*- coding: utf-8 -*-
"""把残留的四川/广安地名统一为「青海·海东」口径
背景：demo 原型是四川广安的数据，之前只做了「广安→海东」的字面替换，
      留下三类不一致：
        1) 籍贯/出生地写成「四川海东、四川南充」——海东在青海，不在四川
        2) 简历/家庭里「海东市岳池县」——岳池是四川县名
        3) 郑海燕拟任「邓小平故里管理局」——广安机构
      以及「四川省XX奖」挂在海东干部身上。

口径：
  · 四川省 → 青海省（奖项、系统称号）
  · 四川<地名> → 青海<海东区县>
  · 四川大学 / 四川农业大学 / 四川师范大学 **保留**（真实高校，在职学历合理）
  · 邓小平故里管理局 → 海东市文化广播电视和旅游局（与本人现职同系统，履历连贯）

作用范围：demo 源页（pad.html / admin.html）+ 正式工程 wwwroot 副本
（改完重新抽取 seed_cadres.json 再灌库，保证三处一致）
"""
import os
import re
import subprocess

RMSYS = '/data/www/files/rmsys'
WWW = '/data/www/files/rmsys-app/backend/src/Rmsys.Api/wwwroot'

# 顺序敏感：先「四川省」，再具体地名，最后机构
MAP = [
    ('四川省', '青海省'),
    ('四川海东', '青海海东'),
    ('四川南充', '青海乐都'),
    ('四川武胜', '青海平安'),
    ('四川岳池', '青海民和'),
    ('四川邻水', '青海互助'),
    ('四川华蓥', '青海化隆'),
    ('四川蓬安', '青海循化'),
    ('四川渠县', '青海乐都'),
    ('海东市岳池县', '海东市乐都区'),
    ('海东市武胜县', '海东市平安区'),
    ('海东市华蓥中学', '海东市乐都区第一中学'),
    ('邓小平故里管理局', '海东市文化广播电视和旅游局'),
]

TARGETS = [
    os.path.join(RMSYS, 'pad.html'),
    os.path.join(RMSYS, 'admin.html'),
    os.path.join(WWW, 'pad.html'),
    os.path.join(WWW, 'admin.html'),
]

report = {}
for p in TARGETS:
    if not os.path.exists(p):
        print('跳过（不存在）：', p)
        continue
    s = open(p, encoding='utf-8').read()
    orig = s
    counts = {}
    for a, b in MAP:
        n = s.count(a)
        if n:
            s = s.replace(a, b)
            counts[a] = n
    if s != orig:
        open(p, 'w', encoding='utf-8').write(s)
        report[os.path.relpath(p, '/data/www/files')] = counts
    else:
        report[os.path.relpath(p, '/data/www/files')] = '(无改动)'

print('=== 替换明细 ===')
for f, c in report.items():
    if c == '(无改动)':
        print('  %-46s 无改动' % f)
    else:
        print('  %-46s %d 类 %d 处' % (f, len(c), sum(c.values())))
        for k, v in c.items():
            print('       %-12s → %-22s %d 处' % (k, dict(MAP)[k], v))

# ---------- 复查：是否还有不该留的 ----------
print()
print('=== 复查（应只剩高校名与「海东市」本体）===')
KEEP_PAT = re.compile(r'四川(大学|农业大学|师范大学)')
for p in TARGETS:
    if not os.path.exists(p):
        continue
    s = open(p, encoding='utf-8').read()
    bad = []
    for m in re.finditer(r'.{0,10}(四川|广安|邓小平).{0,12}', s):
        frag = m.group(0)
        if KEEP_PAT.search(frag):
            continue
        if '四川' in frag or '广安' in frag or '邓小平' in frag:
            bad.append(frag.strip())
    name = os.path.relpath(p, '/data/www/files')
    if bad:
        print('  %-46s 残留 %d 处' % (name, len(bad)))
        for x in set(bad):
            print('       ! %s' % x)
    else:
        print('  %-46s 干净 ✓' % name)

# ---------- 重新抽取种子 ----------
print()
print('=== 重新抽取 seed_cadres.json ===')
r = subprocess.run(['node', 'tools/extract_seed.js'],
                   cwd='/data/www/files/rmsys-app/backend', capture_output=True, text=True)
print(r.stdout.strip() or r.stderr.strip())
