#!/usr/bin/env python3
"""Crawl hbmhg.huaibei.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://hbmhg.huaibei.gov.cn"
COLUMN_URL = "https://hbmhg.huaibei.gov.cn/content/column/4697996"
SITE_NAME = "hb_lh_tzgg"
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 extract_div_by_class(html, class_pattern):
    """Extract HTML content of a <div> with matching class, handling nested divs."""
    m = re.search(r'(<div[^>]*class="[^"]*' + class_pattern + r'[^"]*"[^>]*>)', html)
    if not m:
        return ""
    start = m.start()
    content = html[start:]
    depth = 0
    for i, c in enumerate(content):
        if content[i:i+4] == '<div':
            depth += 1
        elif content[i:i+6] == '</div>':
            depth -= 1
            if depth == 0:
                return content[len(m.group(1)):i].strip()
    return ""


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">', html)
    dates = re.findall(r'<span[^>]*class="right date"[^>]*>([^<]+)</span>', html)
    result = []
    for i, (href, title) in enumerate(items):
        date = dates[i].strip() if i < len(dates) else ""
        url = urljoin(BASE, href) if not href.startswith('http') else href
        result.append({"url": url, "title": title.strip(), "date": date})
    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")

        content_html = extract_div_by_class(html, r'ls-article-info[^"]*j-fontContent')
        if not content_html:
            content_html = extract_div_by_class(html, r'wzcon[^"]*j-fontContent')
        if not content_html:
            return ""

        # Check for attachment links
        attachments = []
        for href in re.findall(r'href="([^"]*\.(?:pdf|doc|docx|xls|xlsx|zip|rar))"', content_html, re.I):
            full = urljoin(url, href)
            a_match = re.search(r'<a[^>]*href="' + re.escape(href) + r'"[^>]*>(.*?)</a>', content_html, re.I | re.DOTALL)
            text = ""
            if a_match:
                text = re.sub(r'<[^>]+>', '', a_match.group(1)).strip()
            if not text:
                text = href.split('/')[-1].rsplit('.', 1)[0]
            attachments.append(f"[{text}]({full})")

        if attachments:
            content_html += '\n\n**附件：**\n' + '\n'.join(attachments)

        return content_html
    except Exception as e:
        print(f"  Detail error: {e}")
        return ""


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")

    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)
            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
            date = item["date"][:10] if item["date"] else ""
            ts = 0
            if date:
                try:
                    ts = int(datetime.strptime(date, "%Y-%m-%d").timestamp())
                except:
                    pass
            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"], date,
                       ts, 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()
