#!/usr/bin/env python3
"""给所有 html_table_to_html 函数体强制加 BeautifulSoup 局部导入
（处理全局缺 import 或局部导入作用域不可见的情况）
"""
import os, glob, ast

DIR = '/root/gov_crawler'

OLD = 'def html_table_to_html(table, base_url=""):\n    """保留 HTML 表格结构，仅将相对链接/图片转绝对 URL"""\n    tbl = BeautifulSoup(str(table), \'html.parser\')'
NEW = 'def html_table_to_html(table, base_url=""):\n    """保留 HTML 表格结构，仅将相对链接/图片转绝对 URL"""\n    from bs4 import BeautifulSoup\n    tbl = BeautifulSoup(str(table), \'html.parser\')'

fixed = []
for p in glob.glob(os.path.join(DIR, 'crawl_*.py')):
    s = open(p).read()
    if 'def html_table_to_html' not in s:
        continue
    if OLD in s:
        s = s.replace(OLD, NEW)
        try:
            ast.parse(s)
            open(p, 'w').write(s)
            fixed.append(os.path.basename(p))
        except Exception as e:
            print(f"FAIL {os.path.basename(p)}: {e}")
    else:
        # 已修复或不同结构
        if 'from bs4 import BeautifulSoup\n    tbl = BeautifulSoup(str(table)' not in s:
            print(f"DIFF {os.path.basename(p)}: structure differs")

print(f"FIXED ({len(fixed)}):")
for f in fixed:
    print('  ', f)
