#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
永修县环保局-通知公告爬虫
crawl_yongxiu_gzdt_hjbhj.py
列表: ul.info-list > li.td01 > a[title] 标题 + span 日期
分页: index.html + index_2~5.html (5页, 20条/页)
详情: div#content.xl-text, 标题 meta[ArticleTitle]/p.mainTitle
详情404时使用 [标题](原文URL) 回退
"""
import re, json, time, sys, os, sqlite3
from datetime import datetime, timedelta
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin

BASE_URL = "http://www.yongxiu.gov.cn"
LIST_PATH = "/bmgkxx/hjbhj/gzdt_3117/gggs_3119"
LIST_URL = BASE_URL + LIST_PATH + "/index.html"
SITE_NAME = "永修县环保局-通知公告"
GROUP = "江西"
DB_PATH = os.getenv("SEARCH_DB", "/root/search.db")
INCREMENTAL_DAYS = 7
MAX_PAGES = 5

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
}
TIMEOUT = 20
session = requests.Session()
session.headers.update(HEADERS)

def fetch(url):
    resp = session.get(url, timeout=TIMEOUT)
    resp.encoding = "utf-8"
    return resp

def parse_list(html):
    """解析列表页 — ul.info-list > li.td01 > a[title] + span"""
    soup = BeautifulSoup(html, "html.parser")
    items = []
    ul = soup.find("ul", class_="info-list")
    if not ul:
        return items
    for li in ul.find_all("li", class_="td01", recursive=False):
        a = li.find("a", href=True)
        if not a:
            continue
        title = a.get("title") or a.get_text(strip=True)
        if not title:
            continue
        href = a["href"].strip()
        if href.startswith("/"):
            href = BASE_URL + href
        elif not href.startswith("http"):
            href = BASE_URL + LIST_PATH + "/" + href
        date_span = li.find("span")
        date_str = date_span.get_text(strip=True)[:10] if date_span else ""
        items.append((title.strip(), href, date_str))
    return items

def parse_detail(html_text, url, list_title=""):
    """解析详情页 — 注意详情可能404，空内容回退"""
    soup = BeautifulSoup(html_text, "html.parser")
    
    # 标题
    title = ""
    meta_t = soup.find("meta", attrs={"name": re.compile(r"ArticleTitle", re.I)})
    if meta_t and meta_t.get("content"):
        title = meta_t["content"].strip()
    if not title:
        h = soup.find("p", class_="mainTitle")
        if h:
            title = h.get_text(strip=True)
    if not title:
        title_m = re.search(r'<p\s+class="mainTitle"[^>]*>(.*?)</p>', html_text, re.S)
        if title_m:
            title = re.sub(r'<[^>]+>', '', title_m.group(1)).strip()
    
    # 日期
    pub_date = ""
    meta_d = soup.find("meta", attrs={"name": re.compile(r"PubDate", re.I)})
    if meta_d and meta_d.get("content"):
        pub_date = meta_d["content"].strip()[:10]
    if not pub_date:
        dm = re.search(r"(\d{4}-\d{2}-\d{2})", html_text)
        if dm:
            pub_date = dm.group(1)
    
    # 正文 — div#content.xl-text
    content = ""
    content_div = soup.find("div", id="content")
    if not content_div:
        content_div = soup.find("div", class_="xl-text")
    if not content_div:
        content_div = soup.find("div", class_=re.compile(r"TRS_UEDITOR|TRS_WEB", re.I))
    
    if content_div:
        paragraphs = []
        for child in content_div.children:
            if child.name == "p":
                p_html = str(child)
                p_html = re.sub(r'<a[^>]*href="([^"]*)"[^>]*>([^<]*)</a>', r'[\2](\1)', p_html)
                p_html = re.sub(r'<img[^>]*src="([^"]*)"[^>]*>', r'![](\1)', p_html)
                text = re.sub(r'<[^>]+>', '', p_html).strip()
                text = re.sub(r'\s+', ' ', text)
                text = re.sub(r'&nbsp;', ' ', text).strip()
                if text:
                    paragraphs.append(text)
            elif child.name == "div":
                for p in child.find_all("p"):
                    p_html = str(p)
                    p_html = re.sub(r'<a[^>]*href="([^"]*)"[^>]*>([^<]*)</a>', r'[\2](\1)', p_html)
                    p_html = re.sub(r'<img[^>]*src="([^"]*)"[^>]*>', r'![](\1)', p_html)
                    text = re.sub(r'<[^>]+>', '', p_html).strip()
                    text = re.sub(r'\s+', ' ', text)
                    text = re.sub(r'&nbsp;', ' ', text).strip()
                    if text:
                        paragraphs.append(text)
            elif child.name == "table":
                rows = []
                for tr in child.find_all("tr"):
                    cells = [td.get_text(" ", strip=True) for td in tr.find_all(["td", "th"])]
                    if cells:
                        rows.append("| " + " | ".join(cells) + " |")
                if rows:
                    row0 = rows[0]
                    sep = "| " + " | ".join(["---"] * (row0.count("|") - 1)) + " |"
                    paragraphs.append("\n".join(rows[:1]) + "\n" + sep + "\n" + "\n".join(rows[1:]))
        if paragraphs:
            content = "\n\n".join(paragraphs)
        else:
            content = re.sub(r'<[^>]+>', '', str(content_div)).strip()
            content = re.sub(r'\s+', ' ', content).strip()
    
    # 附件
    attachments = []
    scope = content_div or soup
    for a_tag in scope.find_all("a", href=True):
        ahref = a_tag["href"].strip().lower()
        if re.search(r"\.(pdf|doc|docx|xls|xlsx|zip|rar)$", ahref):
            full_url = urljoin(url, a_tag["href"].strip())
            attachments.append({
                "name": a_tag.get_text(strip=True) or full_url.split("/")[-1],
                "url": full_url
            })
    
    # 空内容回退 — 标题+链接+附件
    if len(content.strip()) < 20:
        fallback_title = title or list_title or url.split("/")[-1].replace(".html", "").replace("t", "20")
        content = f'<p><a href="{url}">{fallback_title}</a></p>'
        if attachments:
            content += "\n\n附件："
            for att in attachments:
                content += f"\n  - [{att['name']}]({att['url']})"
    
    return title, pub_date, content, attachments


def incremental_filter(items):
    cutoff = datetime.now() - timedelta(days=INCREMENTAL_DAYS)
    filtered = []
    for title, url, date_str in items:
        try:
            if date_str:
                item_date = datetime.strptime(date_str, "%Y-%m-%d")
                if item_date >= cutoff:
                    filtered.append((title, url, date_str))
            else:
                filtered.append((title, url, date_str))
        except:
            filtered.append((title, url, date_str))
    return filtered


def main():
    is_incremental = any(arg in sys.argv for arg in ["--incremental", "incremental", "inc"])
    
    page_urls = [LIST_URL]
    for i in range(2, MAX_PAGES + 1):
        page_urls.append(BASE_URL + LIST_PATH + f"/index_{i}.html")
    
    all_items = []
    for idx, url in enumerate(page_urls):
        try:
            resp = fetch(url)
            html_text = resp.text
            items = parse_list(html_text)
            print(f"  Page {idx+1}/{MAX_PAGES}: {len(items)} items", file=sys.stderr)
            all_items.extend(items)
            time.sleep(0.3)
        except Exception as e:
            print(f"  Page {idx+1} error: {e}", file=sys.stderr)
    
    print(f"  Total: {len(all_items)}", file=sys.stderr)
    
    if is_incremental:
        all_items = incremental_filter(all_items)
        print(f"  Incremental ({INCREMENTAL_DAYS}d): {len(all_items)}", file=sys.stderr)
    
    seen = set()
    unique = []
    for item in all_items:
        if item[1] not in seen:
            seen.add(item[1])
            unique.append(item)
    print(f"  Unique: {len(unique)}", file=sys.stderr)
    
    saved = 0
    skipped = 0
    errors = 0
    for idx, (title, url, list_date) in enumerate(unique):
        try:
            resp = fetch(url)
            html_text = resp.text
            
            # 即使404也尝试解析（空内容会触发回退）
            det_title, det_date, content, attachments = parse_detail(html_text, url, title)
            final_title = det_title or title
            final_date = det_date or list_date
            
            content_text = content[:50000] if content else ''
            summary = re.sub(r'\s+', ' ', content_text[:200]).strip() or final_title
            att_json = json.dumps(attachments, ensure_ascii=False) if attachments else ''
            
            conn = sqlite3.connect(DB_PATH, timeout=10)
            c = conn.cursor()
            c.execute('''INSERT OR IGNORE INTO gov_raw 
                (page_url, title, publish_date, site_name, group_name, summary, content, attachments, source_url)
                VALUES (?,?,?,?,?,?,?,?,?)''',
                (url, final_title, final_date, SITE_NAME, GROUP,
                 summary, content_text, att_json, url))
            if c.rowcount > 0:
                saved += 1
            else:
                skipped += 1
            conn.commit()
            conn.close()
            if (idx + 1) % 20 == 0:
                print(f"  [{idx+1}/{len(unique)}] saved {saved}, skipped {skipped}, errors {errors}", file=sys.stderr)
            time.sleep(0.3)
        except Exception as e:
            print(f"  [{idx+1}] ERROR {title[:30]}: {e}", file=sys.stderr)
            errors += 1
            time.sleep(0.5)
    
    print(f"\n{'='*50}", file=sys.stderr)
    print(f"[{SITE_NAME}] Done! Saved: {saved}, Skipped: {skipped}, Errors: {errors}", file=sys.stderr)
    print(f"{'='*50}", file=sys.stderr)


if __name__ == "__main__":
    main()
