#!/usr/bin/env python3
"""修复 html_table_to_html 中 BeautifulSoup 未定义（脚本用局部导入 as BS 的情况）
在函数体内补: from bs4 import BeautifulSoup
"""
import os, glob, ast

DIR = '/root/gov_crawler'

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
    # 函数体内有 BeautifulSoup 但无导入
    if 'BeautifulSoup(str(table)' in s and 'from bs4 import BeautifulSoup' not in s:
        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\')'
        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}")

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