"""r312: 批量合并 29 组 URL 分叉重复记录。
规则：同 id 多条记录，按字段完整度评分保留最完整那条，删除其他；同步从 VD 移除被删 url。
"""
import re, json, os
from datetime import datetime

path = 'index_main.html'
html = open(path, encoding='utf-8').read()
before_size = len(html.encode('utf-8'))

report = json.load(open('_r309_dup_report.json', encoding='utf-8'))
groups = report['conflict_url_diverge']
print(f"共 {len(groups)} 组待合并")

# 收集所有 PROGRAMS 记录的位置
def find_all_records(html):
    """返回 [(start, end, block_text, id)]"""
    records = []
    for m in re.finditer(r'\{id:"([^"]+)"', html):
        rid = m.group(1)
        start = m.start() - 1  # the {
        # find matching close brace
        depth = 0
        i = start
        while i < len(html):
            c = html[i]
            if c == '{':
                depth += 1
            elif c == '}':
                depth -= 1
                if depth == 0:
                    end = i + 1
                    break
            i += 1
        records.append((start, end, html[start:end], rid))
    return records

records = find_all_records(html)
print(f"PROGRAMS 总记录数: {len(records)}")

# 按 id 分组
from collections import defaultdict
by_id = defaultdict(list)
for rec in records:
    by_id[rec[3]].append(rec)

def score(block):
    """字段完整度评分"""
    s = 0
    # ddl 不是 待补
    m = re.search(r'ddl:"([^"]*)"', block)
    if m and m.group(1) and m.group(1) != '待补':
        s += 2
    # tui 不是 待补
    m = re.search(r'tui:"([^"]*)"', block)
    if m and m.group(1) and m.group(1) != '待补':
        s += 2
    # test.cls 非空
    m = re.search(r'test:\{cls:"([^"]*)"', block)
    if m and m.group(1):
        s += 1
    # dur 非空
    m = re.search(r'dur:"([^"]*)"', block)
    if m and m.group(1):
        s += 1
    # lang 非空
    m = re.search(r'lang:"([^"]*)"', block)
    if m and m.group(1):
        s += 1
    # n 是中文（长度>1且含中文字符）
    m = re.search(r'n:"([^"]*)"', block)
    if m and re.search(r'[\u4e00-\u9fff]', m.group(1)):
        s += 1
    # url 长度（语义命名通常更长）
    m = re.search(r'url:"([^"]*)"', block)
    if m:
        s += len(m.group(1)) / 50.0
    return s

# 对每组，决定保留哪条、删除哪些
to_delete = []  # list of (start, end, block, reason)
for g in groups:
    gid = g['id']
    if gid not in by_id:
        print(f"  [WARN] id {gid} not found in current PROGRAMS")
        continue
    recs = by_id[gid]
    if len(recs) < 2:
        print(f"  [SKIP] id {gid} only 1 record now")
        continue
    # 评分
    scored = [(score(r[2]), r) for r in recs]
    scored.sort(key=lambda x: -x[0])
    keep_score, keep_rec = scored[0]
    print(f"  id={gid}: keep score={keep_score:.2f} url={re.search(r'url:\"([^\"]*)\"', keep_rec[2]).group(1)}")
    for sc, r in scored[1:]:
        url_m = re.search(r'url:"([^"]*)"', r[2])
        n_m = re.search(r'n:"([^"]*)"', r[2])
        print(f"       delete score={sc:.2f} n={n_m.group(1) if n_m else '?'} url={url_m.group(1) if url_m else '?'}")
        to_delete.append((r[0], r[1], r[2], gid))

print(f"\n共删除 {len(to_delete)} 条记录")

# 从后往前删（避免位置偏移）
to_delete.sort(key=lambda x: -x[0])
new_html = html
removed_urls = []
for start, end, block, gid in to_delete:
    url_m = re.search(r'url:"([^"]*)"', block)
    if url_m:
        removed_urls.append(url_m.group(1))
    # 连同前导逗号一起删
    if start > 0 and new_html[start-1] == ',':
        del_start = start - 1
    else:
        del_start = start
    new_html = new_html[:del_start] + new_html[end:]

# 从 VD 集合移除被删 url
for url in removed_urls:
    cnt = new_html.count(f'"{url}"')
    new_html = new_html.replace(f'"{url}",', '').replace(f'"{url}"', '')
    print(f"  VD remove {url}: {cnt} occurrence(s)")

# 写回
open(path, 'w', encoding='utf-8').write(new_html)
after_size = len(new_html.encode('utf-8'))
print(f"\nfile size: {before_size} -> {after_size} (delta {after_size - before_size})")

# 校验
import subprocess
for script in ['final_check.py', '_vd_check.py']:
    r = subprocess.run(['python', script], capture_output=True, text=True)
    print(f"\n=== {script} ===")
    print(r.stdout[-600:])
    if r.returncode != 0:
        print("STDERR:", r.stderr[-500:])
