#!/usr/bin/env python3
"""金溪县人民政府-环境保护 (jinxi.gov.cn) 爬虫

CMS: 浙江政企CMS (ZJEG)
列表: /col/col21169/index.html?number=W00004W00004W00010
      XML datastore 嵌入在页面 <div id="55624/55625/55645"> 中
详情: /art/YYYY/MM/DD/art_XXXXX_XXXXXXX.html
      title: <!--<$[标题]>begin-->TITLE<!--<$[标题]>end-->
      content: <!--ZJEG_RSS.content.begin-->...<!--ZJEG_RSS.content.end-->
日期: 从详情页面提取 (YYYY-MM-DD)
"""

import os, sqlite3, re, time, requests, sys
from datetime import datetime, date, timezone, timedelta
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib3 import disable_warnings, exceptions
disable_warnings(exceptions.InsecureRequestWarning)

SITE_NAME = "金溪县-环境保护"
LIST_URL = "https://www.jinxi.gov.cn/col/col21169/index.html?number=W00004W00004W00010"
BASE = "https://www.jinxi.gov.cn"
DB_PATH = os.environ.get("DB_PATH", "/root/search.db")
CUTOFF = (datetime.now(timezone.utc) - timedelta(days=365*3)).strftime("%Y-%m-%d")
HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
MAX_WORKERS = 6

UNIT_IDS = ['55624', '55625', '55645']


def fetch(url, max_retry=3):
    for att in range(max_retry):
        try:
            r = requests.get(url, headers=HEADERS, timeout=20, verify=False)
            r.encoding = "utf-8"
            if r.status_code == 200:
                return r.text
        except Exception as e:
            if att < max_retry - 1:
                time.sleep(2)
    return None


def parse_list_items(html):
    """Parse embedded XML datastore from the list page"""
    items = []
    for uid in UNIT_IDS:
        m = re.search(f'<div[^>]*id="{uid}"[^>]*>(.*?)</div>', html, re.S)
        if not m:
            print(f"  [WARN] unitid={uid} not found")
            continue
        xml = m.group(1)
        # Find all records
        for rec in re.finditer(r'<record>(.*?)</record>', xml, re.S):
            rec_html = rec.group(1)
            # Extract href and title
            a_m = re.search(r'<a[^>]*href="([^"]+)"[^>]*>([^<]+)</a>', rec_html)
            if not a_m:
                continue
            url = a_m.group(1)
            title = a_m.group(2).strip()
            if not url.startswith("http"):
                url = BASE + url if url.startswith("/") else BASE + "/" + url
            # Extract date from the record
            date_str = ""
            d_m = re.search(r'(\d{4}[-/]\d{2}[-/]\d{2})', rec_html)
            if d_m:
                date_str = d_m.group(1).replace("/", "-")
            # Only include items within 3 years
            if date_str and date_str < CUTOFF:
                continue
            items.append({"title": title, "url": url, "pub_date": date_str})
    return items


def fetch_detail(url):
    """Extract full title + content from detail page"""
    html = fetch(url)
    if not html:
        return "", ""

    # Title from comment markers
    title = ""
    m = re.search(r'<!--<\$\[(?:标题|title)\]>begin-->(.*?)<!--<\$\[(?:标题|title)\]>end-->', html)
    if m:
        title = m.group(1).strip()
    if not title:
        m = re.search(r'class="[^"]*con-title[^"]*"[^>]*>(.*?)</p>', html, re.S)
        if m:
            title = re.sub(r'<[^>]+>', '', m.group(1)).strip()
    if not title:
        m = re.search(r'<title>(.*?)</title>', html)
        if m:
            title = m.group(1).strip()

    # Content from ZJEG markers
    content = ""
    m = re.search(r'<!--ZJEG_RSS\.content\.begin-->(.*?)<!--ZJEG_RSS\.content\.end-->', html, re.S)
    if m:
        content = m.group(1).strip()
    if not content:
        m = re.search(r'<div[^>]*id="zoom"[^>]*>(.*?)</div>', html, re.S)
        if m:
            content = m.group(1).strip()
    # Clean script/style
    content = re.sub(r'<script[^>]*>.*?</script>', '', content, flags=re.S)
    content = re.sub(r'<style[^>]*>.*?</style>', '', content, flags=re.S)

    # Extract date from detail page
    date_str = ""
    for d in re.finditer(r'(\d{4}[-/]\d{2}[-/]\d{2})', html):
        ctx = html[max(0,d.start()-50):d.end()+20]
        if any(kw in ctx for kw in ['date', '时间', '发布', '日期', 'publish', 'Date', '生成日期']):
            date_str = d.group(1).replace("/", "-")
            break
    # Fallback: find the first date near sp_time
    if not date_str:
        for d in re.finditer(r'(\d{4}[-/]\d{2}[-/]\d{2})', html):
            ctx = html[max(0,d.start()-30):d.end()+10]
            if 'sp_time' in ctx or 'time' in ctx.lower():
                date_str = d.group(1).replace("/", "-")
                break

    return title, content, date_str


def main():
    test = "--test" in sys.argv
    mode = "TEST" if test else "FULL"
    print(f"\n=== {SITE_NAME} ({mode}) ===", flush=True)

    # Fetch list page
    html = fetch(LIST_URL)
    if not html:
        print("  [FAIL] Cannot fetch list page")
        return

    items = parse_list_items(html)
    print(f"  Found {len(items)} items within 3yr", flush=True)

    if not items:
        print("  No items to crawl")
        return

    if test:
        items = items[:3]
        print(f"  TEST mode: {len(items)} items", flush=True)

    # Fetch details
    conn = None if test else sqlite3.connect(DB_PATH, timeout=60)
    cursor = conn.cursor() if conn else None
    total_new = 0
    done = 0

    for i, item in enumerate(items):
        print(f"  [{i+1}/{len(items)}] {item['title'][:40]}... ", end="", flush=True)
        title, content, pub_date = fetch_detail(item["url"])
        if not title:
            title = item["title"]
        if not pub_date:
            pub_date = item["pub_date"]

        # Clean title (remove comment marker artifacts)
        title = re.sub(r'begin-->|end-->', '', title).strip()

        if test:
            print(f"title={title[:50]} content={len(content)}B date={pub_date}")
            continue

        try:
            cursor.execute(
                "INSERT OR IGNORE INTO gov_raw (site_name, title, page_url, content, publish_date, summary, tags) VALUES (?,?,?,?,?,?,?)",
                (SITE_NAME, title[:500], item["url"], content, pub_date, "", "环境保护"),
            )
            if cursor.rowcount > 0:
                total_new += 1
                print(f"{len(content)}B")
            else:
                print("skip")
        except Exception as e:
            print(f"DB error: {e}")

        done += 1
        if done % 20 == 0 and conn:
            conn.commit()

    if conn:
        conn.commit()
        # Update FTS
        conn.execute(
            "INSERT INTO gov_search(rowid, title, site_name, summary) "
            "SELECT r.rowid, r.title, r.site_name, r.summary "
            "FROM gov_raw r WHERE r.rowid NOT IN (SELECT rowid FROM gov_search) AND r.site_name=?",
            (SITE_NAME,)
        )
        conn.commit()
        c = conn.execute("SELECT COUNT(*) FROM gov_raw WHERE site_name=?", (SITE_NAME,))
        cnt = c.fetchone()[0]
        conn.close()
        print(f"\n=== 完成 ===", flush=True)
        print(f"  新增: {total_new}条", flush=True)
        print(f"  累计: {cnt}条", flush=True)


if __name__ == "__main__":
    main()
