#!/usr/bin/env python3
"""修复 6 个嵌套函数版 html_table_to_markdown（字符串输入, 无 BeautifulSoup）
直接返回原始 HTML 表格结构（不再转 markdown 管道表）
"""
import os, re, ast

DIR = '/root/gov_crawler'
TARGETS = ['crawl_luanxian.py', 'crawl_luanxian_854.py', 'crawl_lufeng.py',
           'crawl_lufeng_tzgg.py', 'crawl_luliang.py', 'crawl_luojiang.py']

# 匹配嵌套函数: 4空格缩进 def, 函数体 8空格缩进, 到下一个非 8空格缩进行结束
FN_RE = re.compile(
    r'    def html_table_to_markdown\(html_table\):.*?(?=\n    [a-zA-Z_])',
    re.DOTALL
)

NEW_FN = '''    def html_table_to_markdown(html_table):
        # 保留 HTML 表格结构（不再转 markdown 管道表）
        return html_table'''

for name in TARGETS:
    path = os.path.join(DIR, name)
    if not os.path.exists(path):
        print(f"SKIP {name}: not found")
        continue
    s = open(path).read()
    m = FN_RE.search(s)
    if not m:
        print(f"FAIL {name}: pattern not matched")
        continue
    try:
        new_s = s[:m.start()] + NEW_FN + s[m.end():]
        ast.parse(new_s)
        open(path, 'w').write(new_s)
        print(f"FIXED {name}")
    except Exception as e:
        print(f"FAIL {name}: {e}")
