#!/usr/bin/env python3
"""
Crawl 杭锦后旗人民政府 - 通知公告
http://www.hjhq.gov.cn/zwgk/tzgg/
"""
import requests, re, sqlite3, sys, time, hashlib
from datetime import datetime, timedelta
from urllib.parse import urljoin
import os

DB_PATH = os.getenv("SEARCH_DB", "/root/search.db")
SITE_NAME = '杭锦后旗人民政府 - 通知公告'
BASE_URL = 'http://www.hjhq.gov.cn'
LIST_URL = 'http://www.hjhq.gov.cn/zwgk/tzgg/'
CUTOFF_DATE = (datetime.now() - timedelta(days=3*365)).strftime('%Y-%m-%d')

HEADERS = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
}

session = requests.Session()
session.headers.update(HEADERS)

def parse_list(html):
    items = []
    for m in re.finditer(
        r'<div class="module-list-item">\s*<a href="([^"]*)">\s*<span class="tl">(.*?)</span>\s*<span class="date">(\d{4}-\d{2}-\d{2})</span>\s*</a>\s*</div>',
        html, re.DOTALL
    ):
        href, title, date = m.group(1), m.group(2).strip(), m.group(3)
        url = urljoin(LIST_URL, href)
        items.append({'title': title, 'url': url, 'date': date})
    return items

def fetch_detail(url):
    resp = session.get(url, timeout=30)
    resp.encoding = 'utf-8'
    html = resp.text
    tm = re.search(r'<meta name="ArticleTitle" content="([^"]*)"', html)
    if tm:
        title = tm.group(1).strip()
    else:
        tm = re.search(r'<div class="detail-title">(.*?)</div>', html)
        title = tm.group(1).strip() if tm else ''
    dm = re.search(r'<meta name="PubDate" content="([^"]*)"', html)
    if dm:
        date_str = dm.group(1)[:10]
    else:
        dm = re.search(r'发布时间：(\d{4}-\d{2}-\d{2})', html)
        date_str = dm.group(1) if dm else ''
    cm = re.search(r'<div class="detail-cnt" id="detailCnt">(.*?)</div>\s*</div>\s*</div>', html, re.DOTALL)
    if cm:
        content = cm.group(1).strip()
        content = re.sub(r'<script[^>]*>.*?</script>', '', content, flags=re.DOTALL|re.I)
        content = re.sub(r'<style[^>]*>.*?</style>', '', content, flags=re.DOTALL|re.I)
        return title, date_str, content
    return title, date_str, ''

def make_int_id(url):
    return int(hashlib.md5(url.encode()).hexdigest()[:15], 16) % (2**63)

def main():
    is_incremental = 'incremental' in sys.argv
    print(f'=== {SITE_NAME} ===')
    conn = sqlite3.connect(DB_PATH, timeout=60)
    c = conn.cursor()
    inserted, skipped, old_total = 0, 0, 0
    max_pages = 1 if is_incremental else 50
    consecutive_old = 0
    min_pages = 5
    for pg in range(1, max_pages + 1):
        list_url = LIST_URL if pg == 1 else f'{LIST_URL}index_{pg}.html'
        try:
            resp = session.get(list_url, timeout=30)
            resp.encoding = 'utf-8'
            html = resp.text
        except Exception as e:
            print(f'  [ERROR] Page {pg}: {e}')
            time.sleep(2)
            continue
        items = parse_list(html)
        if not items:
            print(f'  Page {pg}: 0 items (end)')
            break
        all_old = all(item['date'] < CUTOFF_DATE for item in items)
        if all_old:
            consecutive_old += 1
            if consecutive_old >= 2 and pg >= min_pages:
                print(f'  Page {pg}: all old, stopping')
                break
        else:
            consecutive_old = 0
        for item in items:
            if item['date'] < CUTOFF_DATE:
                old_total += 1
                continue
            has = c.execute('SELECT 1 FROM gov_raw WHERE page_url=? AND content IS NOT NULL AND content!=\'\'', (item['url'],)).fetchone()
            if has:
                skipped += 1
                continue
            try:
                title, date_str, content = fetch_detail(item['url'])
            except Exception as e:
                print(f'  [ERROR] Detail: {e}')
                time.sleep(1)
                continue
            if not content and not title:
                skipped += 1
                continue
            final_title = title or item['title']
            final_date = date_str or item['date']
            int_id = make_int_id(item['url'])
            date_rank = int(final_date.replace('-', '')) if final_date else 0
            summary = re.sub(r'<[^>]+>', '', content)[:200] if content else final_title
            summary = re.sub(r'\s+', ' ', summary).strip()
            try:
                c.execute(
                    'INSERT OR IGNORE INTO gov_raw(id, site_name, source_url, page_url, title, publish_date, content, summary, date_rank) VALUES(?,?,?,?,?,?,?,?,?)',
                    (int_id, SITE_NAME, item['url'], item['url'], final_title, final_date, content, summary, date_rank)
                )
                if c.rowcount > 0:
                    inserted += 1
                else:
                    skipped += 1
            except Exception as e:
                print(f'  [DB] {e}')
                skipped += 1
            time.sleep(0.3)
        print(f'  Page {pg}: +{inserted} (skipped {skipped}, >3y {old_total})')
    conn.commit()
    try:
        c2 = conn.cursor()
        # QC20260926 去掉手写 gov_search 整站删除(抢锁源; FTS 由 gov_raw 触发器维护) 
        # c2.execute("DELETE FROM gov_search WHERE rowid IN (SELECT id FROM gov_raw WHERE site_name=?)", (SITE_NAME,))
        rows = c2.execute("SELECT id, title, site_name, summary FROM gov_raw WHERE site_name=?", (SITE_NAME,)).fetchall()
        c2.executemany("INSERT OR IGNORE INTO gov_search(rowid, title, site_name, summary) VALUES(?,?,?,?)", rows)
        conn.commit()
        print(f'  FTS: {len(rows)} records rebuilt')
    except Exception as e:
        print(f'  FTS error: {e}')
    conn.close()
    print(f'\nDone. Inserted {inserted}, Skipped {skipped}, Old {old_total}')

if __name__ == '__main__':
    main()
