import re

html = open('index_main.html', encoding='utf-8').read()

# 用括号深度匹配找到 CATD 数组结束位置
start_marker = 'const CATD=['
start = html.index(start_marker) + len(start_marker) - 1  # 指向 [
depth = 0
i = start
while i < len(html):
    ch = html[i]
    if ch == '[':
        depth += 1
    elif ch == ']':
        depth -= 1
        if depth == 0:
            break
    i += 1
catd_text = html[start:i+1]
print(f'CATD 数组长度: {len(catd_text)} 字符')

# 在 CATD 文本里找独立的 null 词（前后不是字母/引号）
pattern = r'(?<![\w"])(null)(?![\w"])'
null_matches = list(re.finditer(pattern, catd_text))
print(f'找到 {len(null_matches)} 个独立 null 词')
for idx, m in enumerate(null_matches):
    ctx_start = max(0, m.start()-100)
    ctx_end = min(len(catd_text), m.end()+100)
    print(f'\n--- null #{idx+1} 位置 {m.start()} ---')
    print(repr(catd_text[ctx_start:ctx_end]))

# 现在修复：把 null 元素替换成空字符串或删除
# 先看 null 前后的逗号，确保删除后语法正确
new_catd = catd_text
# 从后往前替换，避免位置偏移
for m in reversed(null_matches):
    # 找 null 前后的范围
    s = m.start()
    e = m.end()
    # 向左找逗号（可能是 ",null" 或 "null,"）
    # 向右找逗号
    left = s - 1
    while left >= 0 and catd_text[left] in ' \t\n\r':
        left -= 1
    right = e
    while right < len(catd_text) and catd_text[right] in ' \t\n\r':
        right += 1

    # 判断是 ",null" 还是 "null,"
    if left >= 0 and catd_text[left] == ',' and right < len(catd_text) and catd_text[right] != ',':
        # 模式: ..., null ... -> 删除 ", null"（左逗号+null+空格）
        new_catd = new_catd[:left] + new_catd[right:]
    elif left >= 0 and catd_text[left] == ',' and right < len(catd_text) and catd_text[right] == ',':
        # 模式: ..., null, ... -> 删除 " null,"（null+空格+右逗号），保留左逗号
        new_catd = new_catd[:s] + new_catd[right:]
    else:
        print(f'警告：null 位置上下文异常，无法自动修复')
        print(f'  left={left}, right={right}')
        print(f'  left char={repr(catd_text[left]) if left>=0 else "N/A"}')
        print(f'  right char={repr(catd_text[right]) if right<len(catd_text) else "N/A"}')

# 验证修复后没有 null
remaining = list(re.finditer(pattern, new_catd))
print(f'\n修复后剩余 null 词: {len(remaining)}')

# 写回文件
new_html = html[:start] + new_catd + html[i+1:]
open('index_main.html', 'w', encoding='utf-8').write(new_html)
print(f'文件已写回，新大小: {len(new_html)} 字符')
