#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
漳州台商投资区 - 环评受理情况 (YLcms)
http://tiz.zhangzhou.gov.cn/cms/html/zztstzq/hpslqk/index.html
"""
import sys, os, re, time, requests, sqlite3
from concurrent.futures import ThreadPoolExecutor, as_completed

SEARCH_DB = os.getenv("SEARCH_DB", "/root/search.db")
HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
SITE_ID = "830617491273300000"
LIST_URL = "http://tiz.zhangzhou.gov.cn/cms/sitemanage/index.shtml"
DOMAIN = "http://tiz.zhangzhou.gov.cn"


def get_list_items():
    """获取列表所有项目"""
    items = []
    page = 1
    while True:
        url = f"{LIST_URL}?siteId={SITE_ID}&page={page}"
        try:
            r = requests.get(url, headers=HEADERS, timeout=30)
            r.encoding = "utf-8"
            html = r.text
        except Exception as e:
            print(f"  Page {page} error: {e}")
            break

        links = re.findall(r'<A href="(/cms/html/zztstzq/\d+[^/]*/\d+\.html)"[^>]*>([^<]+)</A>', html)
        dates = re.findall(r'<SPAN class="list-time">([^<]+)</SPAN>', html)

        if not links:
            break

        for i, (href, title) in enumerate(links):
            date = dates[i] if i < len(dates) else ""
            items.append({
                "url": DOMAIN + href,
                "title": title.strip(),
                "date": date.strip(),
                "site": "zztstzq_hpslqk"
            })

        print(f"  Page {page}: {len(links)} items")
        if len(links) < 20:
            break
        page += 1
        time.sleep(0.3)

    return items


def fetch_detail(item):
    """抓取详情页"""
    url = item["url"]
    try:
        r = requests.get(url, headers=HEADERS, timeout=30)
        r.encoding = "utf-8"
        html = r.text
    except Exception:
        return (url, item["title"], "", item["date"], item["site"])

    # Title
    title = item["title"]
    m = re.search(r'<meta name="ArticleTitle"[^>]*content="([^"]*)"', html)
    if m:
        t = m.group(1).strip()
        if t:
            title = t

    # Content
    content = ""
    m = re.search(r'<div[^>]*class="content"[^>]*id="Content"[^>]*>(.*?)</div>', html, re.DOTALL)
    if not m:
        m = re.search(r'class="content"[^>]*id="Content"[^>]*>(.*?)</div>', html, re.DOTALL)
    if m:
        raw = m.group(1).strip()
        raw = re.sub(r'<script[^>]*>.*?</script>', "", raw, flags=re.DOTALL | re.I)
        raw = re.sub(r'<style[^>]*>.*?</style>', "", raw, flags=re.DOTALL | re.I)
        content = raw

    # Date
    date = item["date"]
    if not date:
        m = re.search(r'发布时间[：:]\s*(\d{4}[-/]\d{2}[-/]\d{2})', html)
        if m:
            date = m.group(1)
        else:
            m = re.search(r'<meta name="PubDate"[^>]*content="([^"]*)"', html)
            if m:
                date = m.group(1).split()[0].replace("\u2014", "-")

    return (url, title, content, date, item["site"])


def main():
    total_new = 0

    print("Fetching list...")
    items = get_list_items()
    print(f"  Total: {len(items)} items")

    if not items:
        print("No items found!")
        return

    # Check existing
    conn = sqlite3.connect(SEARCH_DB, timeout=60)
    conn.execute("PRAGMA busy_timeout=30000")
    existing = set(
        r[0] for r in conn.execute(
            "SELECT page_url FROM gov_raw WHERE site_name='zztstzq_hpslqk'"
        ).fetchall()
    )

    new_items = [it for it in items if it["url"] not in existing]
    print(f"  Existing: {len(existing)}, New: {len(new_items)}")

    if not new_items:
        print("All up to date!")
        conn.close()
        return

    print(f"Fetching {len(new_items)} details (5 threads)...")
    done = 0
    with ThreadPoolExecutor(max_workers=5) as pool:
        fut_map = {pool.submit(fetch_detail, item): item for item in new_items}
        for f in as_completed(fut_map):
            url, title, content, date, site = f.result()
            try:
                c = conn.execute(
                    "INSERT OR IGNORE INTO gov_raw (title, page_url, source_url, content, publish_date, site_name) VALUES (?, ?, ?, ?, ?, ?)",
                    (title, url, url, content, date, site)
                )
                conn.commit()
                if c.rowcount > 0:
                    total_new += 1
            except Exception as e:
                print(f"  DB error for {url}: {e}")
            done += 1
            if done % 50 == 0 or done == len(new_items):
                print(f"  {done}/{len(new_items)} processed, new={total_new}")

    print(f"\nDone! {len(new_items)} processed, {total_new} new.")
    conn.close()


if __name__ == "__main__":
    main()
