#!/usr/bin/env python3
"""
normalize_dates_cron.py — 每日兜底清理 gov_raw.publish_date 脏格式
==================================================================
背景：~821 个爬虫直接 INSERT gov_raw（绕过 crawler_lib.push_to_searchdb 的规范化），
可能写入中文格式/长横线/单数字等脏日期，污染 search_app 的时间段过滤和排序。

本脚本增量扫描：只处理非标准格式的行（小结果集），统一为 YYYY-MM-DD。
用法：
    python3 normalize_dates_cron.py            # 扫全库非标准行（快，脏行很少）
    python3 normalize_dates_cron.py --all      # 强制全量（含已标准行检查，慢）
无输出 = 无脏数据（适合 cron 静默）。有脏行时输出修正数量。
"""
import sqlite3
import re
import sys

DB = "/mnt/data/search.db"

# 与 crawler_lib.normalize_pub_date 保持一致的规范化逻辑（独立副本，避免依赖）
DATE_RE = re.compile(
    r'(\d{4})[年\-/\.](\d{1,2})[月\-/\.](\d{1,2})'
    r'|(?<!\d)(\d{4})(\d{2})(\d{2})(?!\d)'
)
EM_DASH_DATE = re.compile(r'(\d{4})[—–](\d{1,2})[—–](\d{1,2})')


def normalize(raw_date):
    if not raw_date:
        return ''
    s = str(raw_date).strip()
    m = DATE_RE.search(s)
    if m:
        if m.group(1):
            y, mo, d = int(m.group(1)), int(m.group(2)), int(m.group(3))
        else:
            y, mo, d = int(m.group(4)), int(m.group(5)), int(m.group(6))
        try:
            import datetime
            datetime.datetime(y, mo, d)
        except ValueError:
            return ''
        return "%04d-%02d-%02d" % (y, mo, d)
    m = EM_DASH_DATE.search(s)
    if m:
        y, mo, d = int(m.group(1)), int(m.group(2)), int(m.group(3))
        return "%04d-%02d-%02d" % (y, mo, d)
    m = re.search(r'(\d{4})-(\d{2})$', s)
    if m:
        return "%s-%s-01" % (m.group(1), m.group(2))
    m = re.search(r'^(\d{4})$', s)
    if m:
        return "%s-01-01" % m.group(1)
    return ''


def main():
    full = '--all' in sys.argv
    conn = sqlite3.connect(DB, timeout=60, isolation_level=None)
    conn.execute('PRAGMA busy_timeout=30000')
    c = conn.cursor()
    if full:
        c.execute("SELECT id, publish_date FROM gov_raw")
    else:
        # 增量：只取非标准格式行（标准 20xx-xx-xx 不碰；1980 前老数据保留原样）
        c.execute(
            "SELECT id, publish_date FROM gov_raw "
            "WHERE publish_date != '' AND publish_date NOT GLOB '20[0-9][0-9]-[0-9][0-9]-[0-9][0-9]'"
        )
    rows = c.fetchall()
    fixed = 0
    cleared = 0
    for rid, pd in rows:
        new = normalize(pd)
        if new != pd:
            if new:
                fixed += 1
            else:
                cleared += 1
            conn.execute('UPDATE gov_raw SET publish_date=? WHERE id=?', (new, rid))
    conn.close()
    if fixed or cleared:
        print("normalize_dates: fixed=%d cleared=%d" % (fixed, cleared))
    # 无输出 = 无脏数据（cron 静默）


if __name__ == '__main__':
    main()
