#!/usr/bin/env python3
"""Crawl 云南湖柏环保科技 - 行业新闻
http://www.ynhbhb.com/index.php?list_1_33.html
"""
import requests, re, sqlite3, sys, time, hashlib
from datetime import datetime, timedelta
from bs4 import BeautifulSoup
import os

DB_PATH = os.getenv("SEARCH_DB", "/root/search.db")
SITE_NAME = '云南湖柏环保 - 行业新闻'
BASE_URL = 'http://www.ynhbhb.com'
LIST_URL = 'http://www.ynhbhb.com/index.php?list_1_33.html'
CUTOFF_DATE = (datetime.now() - timedelta(days=3*365)).strftime('%Y-%m-%d')
MAX_PAGES = 5

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 = []
    soup = BeautifulSoup(html, 'html.parser')
    for ul in soup.find_all('ul'):
        lis = ul.find_all('li', recursive=False)
        if len(lis) < 5:
            continue
        articles = []
        for li in lis:
            a = li.find('a', href=True)
            if not a:
                continue
            href = a['href']
            if 'index.php' not in href or 'list_' in href:
                continue  # skip navigation links
            raw_title = a.get_text(strip=True)
            if not raw_title or len(raw_title) < 10:
                continue
            # Extract date from title (pattern: YYYY.MM.DD or YYYY-MM-DD)
            dm = re.search(r'(\d{4})[.-](\d{1,2})[.-](\d{1,2})', raw_title)
            date_str = ''
            if dm:
                date_str = f'{dm.group(1)}-{int(dm.group(2)):02d}-{int(dm.group(3)):02d}'
                # Remove date suffix from title
                clean_title = re.sub(r'\s*\d{4}[.-]\d{1,2}[.-]\d{1,2}\s*', '', raw_title).strip()
            else:
                clean_title = raw_title
            
            if not href.startswith('http'):
                url = BASE_URL + '/' + href.lstrip('/')
            else:
                url = href
            
            articles.append({'title': clean_title, 'url': url, 'date': date_str, 'raw_title': raw_title})
        
        if len(articles) >= 3:
            return articles
    return items

def fetch_detail(url):
    try:
        resp = session.get(url, timeout=30)
        resp.encoding = 'utf-8'
        html = resp.text
    except:
        return '', ''
    
    # Title from <title> tag, remove site suffix
    tm = re.search(r'<title>(.*?)</title>', html, re.DOTALL|re.I)
    title = ''
    if tm:
        raw = tm.group(1).strip()
        # Remove " - 行业新闻 - 云南湖柏环保科技有限公司" suffix
        title = re.sub(r'\s*-\s*行业新闻\s*-\s*云南湖柏环保科技有限公司\s*$', '', raw).strip()
    
    # Content from div.showinfo
    soup = BeautifulSoup(html, 'html.parser')
    con = soup.find('div', class_='showinfo')
    if con:
        for tag in con.find_all(['script', 'style']):
            tag.decompose()
        return title, str(con).strip()
    
    return title, ''

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 MAX_PAGES
    consecutive_old = 0
    min_pages = 3
    start_time = time.time()
    
    for pg in range(1, max_pages + 1):
        if pg == 1:
            list_url = LIST_URL
        else:
            list_url = f'{BASE_URL}/index.php?list_1_33_{pg}.html'
        
        try:
            resp = session.get(list_url, timeout=30)
            resp.encoding = 'utf-8'
            raw_html = resp.text
        except Exception as e:
            print(f'  [ERROR] Page {pg}: {e}')
            time.sleep(2)
            continue
        
        items = parse_list(raw_html)
        if not items:
            print(f'  Page {pg}: 0 items (end)')
            break
        
        all_old = all(item['date'] and item['date'] < CUTOFF_DATE for item in items if item['date'])
        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'] and 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, content = fetch_detail(item['url'])
            except Exception as e:
                print(f'  [ERROR] Detail: {e}')
                time.sleep(1)
                skipped += 1
                continue
            
            final_title = title or item['title']
            final_date = item['date']
            int_id = int(hashlib.md5(item['url'].encode()).hexdigest()[:15], 16) % (2**63)
            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
            except Exception as e:
                print(f'  [DB] {e}')
                skipped += 1
            time.sleep(0.3)
        
        elapsed = time.time() - start_time
        print(f'  Page {pg}/{max_pages}: +{inserted} (skipped {skipped}, >3y {old_total}) [{elapsed:.0f}s]')
    
    conn.commit()
    # FTS rebuild
    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()
        for r in rows:
            c2.execute("INSERT OR IGNORE INTO gov_search(rowid, title, site_name, summary) VALUES(?,?,?,?)", r)
        conn.commit()
        print(f'  FTS: {len(rows)} records rebuilt')
    except Exception as e:
        print(f'  FTS error: {e}')
    conn.close()
    elapsed = time.time() - start_time
    print(f'\nDone ({elapsed:.0f}s). Inserted {inserted}, Skipped {skipped}, Old {old_total}')

if __name__ == '__main__':
    main()
