# -*- coding: utf-8 -*-
import re, io, sys, json
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
f = r"D:\work buddy\2026-11-05-14-15-52\index_main.html"
raw = open(f, encoding="utf-8").read()

clean = json.load(open(r"D:\work buddy\2026-11-05-14-15-52\clean_list.json", encoding="utf-8"))
remove_det = {g["det"] for g in clean["remove"]}
print("待剔除 det 数:", len(remove_det))

# --- 1. 重建 CATD ---
c0 = raw.index("const CATD=["); c1 = raw.index("\n];", c0)
head = raw[:c0]; tail = raw[c1:]
catd_body = raw[c0+len("const CATD=["):c1]
pat = re.compile(r'\["(?P<s>[^"]+)",\s*"(?P<col>[^"]*)",\s*"(?P<en>[^"]*)",\s*"(?P<cn>[^"]*)",\s*"(?P<deg>[^"]*)",\s*"(?P<url>[^"]*)",\s*"(?P<disc>[^"]*)",\s*"(?P<det>[^"]*)"\]')
kept, dropped = [], 0
for m in pat.finditer(catd_body):
    if m.group("det") in remove_det:
        dropped += 1
    else:
        kept.append(m.group(0))
print("CATD 剔除:", dropped, " 保留:", len(kept))
new_catd = "const CATD=[\n" + ",\n".join(kept) + "\n"
raw2 = head + new_catd + tail

# --- 2. 清理 VERIFIED_DETAILS 中被剔除的 det ---
v0 = raw2.index("const VERIFIED_DETAILS=new Set([")
v1 = raw2.index("]);", v0)
vbody = raw2[v0:v1]
vdet = re.findall(r'"(details/[^"]+\.html)"', vbody)
vkeep = [d for d in vdet if d not in remove_det]
print("VERIFIED_DETAILS 原:", len(vdet), " 清理后:", len(vkeep))
new_v = "const VERIFIED_DETAILS=new Set([" + ",".join('"'+d+'"' for d in vkeep) + "])"
raw2 = raw2[:v0] + new_v + raw2[v1+2:]

# --- 3. 写回（UTF-8 无 BOM） ---
open(f, "w", encoding="utf-8", newline="").write(raw2)
print("已写回。新文件字符数:", len(raw2))

# 复核：重新解析计数
raw3 = open(f, encoding="utf-8").read()
cc0 = raw3.index("const CATD=["); cc1 = raw3.index("const VERIFIED_DETAILS")
n_cat = len(pat.findall(raw3[cc0:cc1]))
p0 = raw3.index("const PROGRAMS=["); p1 = raw3.index("const CATD=[")
n_prog = len(re.findall(r'\{id:"', raw3[p0:p1]))
print("复核 CATD:", n_cat, " PROGRAMS:", n_prog)
