#!/usr/bin/env python3
"""Crawl gxq.anqing.gov.cn - 安庆高新区企业环保信息公开 (Lonsun CMS)"""
import sys, re, json, sqlite3, urllib.request, urllib.error, traceback, ssl
from datetime import datetime
from urllib.parse import urljoin

ssl._create_default_https_context = ssl._create_unverified_context

BASE = "https://gxq.anqing.gov.cn"
COLUMN_URL = "https://gxq.anqing.gov.cn/content/column/75175571"
SITE_NAME = "aq_gxq_qyhb"
DB_PATH = "/root/search.db"
PAGE_SIZE = 20
MAX_PAGES = 5  # 初始5页

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


def fetch_list_page(page):
    url = f"{COLUMN_URL}?pageIndex={page}&pageSize={PAGE_SIZE}"
    req = urllib.request.Request(url, headers=headers)
    resp = urllib.request.urlopen(req, timeout=15)
    return resp.read().decode("utf-8", errors="replace")


def parse_list(html):
    items = re.findall(
        r'<a href="([^"]+)"[^>]*title="([^"]*)"[^>]*class="left">.*?</a>.*?<span[^>]*class="right date"[^>]*>([^<]+)</span>',
        html, re.DOTALL)
    result = []
    for href, title, date_str in items:
        full_url = urljoin(BASE, href) if not href.startswith('http') else href
        result.append({"url": full_url, "title": title.strip(), "date": date_str.strip()})
    return result


def fetch_detail(url):
    try:
        req = urllib.request.Request(url, headers=headers)
        resp = urllib.request.urlopen(req, timeout=15)
        html = resp.read().decode("utf-8", errors="replace")
        m = re.search(r'<div[^>]*class="[^"]*ls-article-info[^"]*j-fontContent[^"]*"[^>]*>(.*?)</div>\s*<div', html, re.DOTALL)
        if not m:
            m = re.search(r'<div[^>]*class="[^"]*ls-article-info[^"]*"[^>]*>(.*?)</div>\s*<div', html, re.DOTALL)
        if not m:
            return ""
        return m.group(1).strip()
    except Exception as e:
        print(f"  Detail error: {e}")
        return ""


def save_to_db(records):
    if not records:
        return 0
    conn = sqlite3.connect(DB_PATH, timeout=60)
    conn.execute("PRAGMA busy_timeout=30000")
    c = conn.cursor()
    count = 0
    for r in records:
        if c.execute("SELECT id FROM gov_raw WHERE source_url=?", (r["url"],)).fetchone():
            continue
        c.execute("""INSERT INTO gov_raw (site_name, source_url, page_url, title, publish_date, date_rank, summary, content)
            VALUES (?,?,?,?,?,?,?,?)""",
                  (SITE_NAME, r["url"], r["url"], r["title"], r["date"],
                   int(datetime.strptime(r["date"], "%Y-%m-%d").timestamp()) if r["date"] else 0,
                   r["content"][:200] if r["content"] else "", r["content"]))
        conn.commit()
        count += 1
    conn.close()
    return count


def main():
    print(f"=== Crawling {SITE_NAME} ===")

    all_items = []
    for page in range(1, MAX_PAGES + 1):
        try:
            html = fetch_list_page(page)
            items = parse_list(html)
            if not items:
                print(f"Page {page}: no items")
                break
            print(f"Page {page}: {len(items)} items")
            all_items.extend(items)
        except Exception as e:
            print(f"Page {page}: error - {e}")
            break

    print(f"Total: {len(all_items)} items")

    # Fetch detail + save sequentially
    saved = 0
    for i, item in enumerate(all_items):
        print(f"[{i+1}/{len(all_items)}] {item['title'][:50]}...")
        try:
            content = fetch_detail(item["url"])
            conn = sqlite3.connect(DB_PATH, timeout=60)
            conn.execute("PRAGMA busy_timeout=30000")
            c = conn.cursor()
            if c.execute("SELECT id FROM gov_raw WHERE source_url=?", (item["url"],)).fetchone():
                print(f"  SKIP")
                conn.close()
                continue
            c.execute("""INSERT INTO gov_raw (site_name, source_url, page_url, title, publish_date, date_rank, summary, content)
                VALUES (?,?,?,?,?,?,?,?)""",
                      (SITE_NAME, item["url"], item["url"], item["title"], item["date"],
                       int(datetime.strptime(item["date"], "%Y-%m-%d").timestamp()) if item["date"] else 0,
                       content[:200] if content else "", content))
            conn.commit()
            conn.close()
            saved += 1
            print(f"  OK: {item['title'][:50]}")
        except Exception as e:
            print(f"  Error: {e}")

    print(f"\n=== Complete: {saved}/{len(all_items)} new records ===")


if __name__ == "__main__":
    main()
