#!/usr/bin/env python3
"""淄博齐翔腾达化工-公示信息 爬虫 (静态)
"""
import os, sqlite3, re, time, requests
from datetime import datetime, date

BASE = "https://qxtd.shandong-energy.com"
COL_URL = BASE + "/349348/349349/"
CUTOFF_DATE = date(2023, 6, 17)
DB_PATH = os.environ.get("DB_PATH", "/root/search.db")
SITE_NAME = "淄博齐翔腾达-公示信息"
HEADERS = {"User-Agent": "Mozilla/5.0"}


def get_article_urls():
    """从列表页提取文章链接"""
    r = requests.get(COL_URL, timeout=30, headers=HEADERS)
    r.encoding = "utf-8"
    html = r.text
    urls = set()
    for m in re.finditer(r'href="(https?://[^"]*?/(?:\d{4}/\d{2}/\d+\.html))"', html):
        urls.add(m.group(1))
    return list(urls)


def extract_content(html):
    """提取 inner_content_con 内部HTML"""
    m = re.search(r'<div class="inner_content_con">', html)
    if not m:
        return ""
    start = m.end()
    depth = 1
    i = start
    while i < len(html) - 5 and depth > 0:
        if html[i:i+4] == '<div' and html[i+4] in (' ', '>', '\n', '\t', '\r'):
            depth += 1
        elif html[i:i+6] == '</div>':
            depth -= 1
        i += 1
    return html[start:i-6].strip()


def fetch_detail(url):
    for att in range(3):
        try:
            r = requests.get(url, timeout=30, headers=HEADERS)
            r.encoding = "utf-8"
            if r.status_code != 200:
                time.sleep(2)
                continue
            html = r.text

            # 标题
            title = ""
            m = re.search(r'<h1 class="auto_cut1">\s*(.*?)\s*</h1>', html)
            if m:
                title = m.group(1).strip()
            if not title:
                m = re.search(r'<title>(.*?)</title>', html)
                if m:
                    title = m.group(1).replace("-淄博齐翔腾达化工股份有限公司", "").strip()

            # 日期
            pub_date = ""
            m = re.search(r'inner_content_date[^>]*>.*?(\d{4})年(\d{2})月(\d{2})日', html)
            if m:
                pub_date = f"{m.group(1)}-{m.group(2)}-{m.group(3)}"
            if not pub_date:
                m = re.search(r'发布日期[：:].*?(\d{4})年(\d{2})月(\d{2})日', html)
                if m:
                    pub_date = f"{m.group(1)}-{m.group(2)}-{m.group(3)}"
            if not pub_date:
                m = re.search(r'(\d{4})-(\d{2})-(\d{2})', html)
                if m:
                    pub_date = f"{m.group(1)}-{m.group(2)}-{m.group(3)}"

            # 正文
            content = extract_content(html)
            if not content:
                content = title

            return (url, title, content, pub_date)
        except:
            if att < 2:
                time.sleep(2)
    return (url, None, None, None)


def main():
    mode = os.environ.get("MODE", "full")
    print(f"=== {SITE_NAME} (mode={mode}) ===", flush=True)

    urls = get_article_urls()
    print(f"  文章链接: {len(urls)}条", flush=True)

    total_new = 0
    for url in urls:
        url2, title, content, pub_date = fetch_detail(url)
        if title is None:
            continue
        if not content:
            content = title
        try:
            d = date.fromisoformat(pub_date[:10]) if pub_date else date.today()
            if d < CUTOFF_DATE:
                print(f"  [跳过] {pub_date} {title[:30]}", flush=True)
                continue
        except:
            pass

        conn = sqlite3.connect(DB_PATH, timeout=60)
        cursor = conn.cursor()
        try:
            cursor.execute("""INSERT OR IGNORE INTO gov_raw (site_name, title, page_url, content, publish_date, summary, date_rank) VALUES (?, ?, ?, ?, ?, ?, ?)""",
                (SITE_NAME, title, url, content, pub_date[:10] if pub_date else "", content, 0))
            if cursor.rowcount > 0:
                total_new += 1
                print(f"  + {title[:40]} ({pub_date})", flush=True)
        except Exception as e:
            print(f"  [DB_ERROR] {e}", flush=True)
        conn.commit()
        cursor.execute("SELECT COUNT(*) FROM gov_raw WHERE site_name=?", (SITE_NAME,))
        cnt = cursor.fetchone()[0]
        conn.close()

    print(f"\n=== 完成 ===", flush=True)
    print(f"  新增: {total_new}条", flush=True)


if __name__ == "__main__":
    main()
