#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""补修 3 个 f-string 内联值的 INSERT OR REPLACE（不含 ? 占位符，走另一套改法）。"""
import io
import os
import shutil
import sys

D = "/root/gov_crawler"
ARCH = os.path.join(D, "Archive")
DRY = "--dry-run" in sys.argv

# 每个文件：把 script_name 列加进列清单，并在 VALUES 的最后一列后加字面量
TARGETS = {
    "crawl_cyx.py": ("(site_name, page_url, title, publish_date, content, summary, date_rank, category)",
                     "'环评审批')"),
    "crawl_fxxh.py": ("(site_name, page_url, title, publish_date, content, summary, date_rank, category)",
                      "'便民通知')"),
    "crawl_zhanhua.py": ("(site_name, page_url, title, publish_date, content, summary, date_rank, category)",
                         "'政府公告')"),
}

for fn, (cols, tail) in TARGETS.items():
    p = os.path.join(D, fn)
    src = io.open(p, encoding="utf-8").read()
    if "script_name" in src and "INSERT OR REPLACE INTO gov_raw" in src:
        # 只看 INSERT 语句那一段里有没有 script_name
        i = src.index("INSERT OR REPLACE INTO gov_raw")
        seg = src[i:i + 700]
        if "script_name" in seg:
            print("   ⏭  %s 已含 script_name，跳过" % fn)
            continue
    n1 = src.count(cols)
    n2 = src.count(tail)
    if n1 != 1 or n2 != 1:
        print("   ❌ %s 锚点命中异常 cols=%d tail=%d" % (fn, n1, n2))
        continue
    new = src.replace(cols, cols[:-1] + ", script_name)")
    new = new.replace(tail, tail[:-1].rstrip() + ", '%s')" % fn)
    # 语法自检
    import ast
    try:
        ast.parse(new)
    except SyntaxError as e:
        print("   ❌ %s 语法失败: %s" % (fn, e))
        continue
    if not DRY:
        os.makedirs(ARCH, exist_ok=True)
        bak = os.path.join(ARCH, fn + ".bak_20260921_replfix")
        if not os.path.exists(bak):
            shutil.copy2(p, bak)
        io.open(p, "w", encoding="utf-8").write(new)
    print("   ✅ %s" % fn)
print()
print("完成%s" % ("  [DRY-RUN]" if DRY else ""))
