#!/usr/bin/env python3
"""陵川县人民政府 — 生态环境局部门工作
http://xxgk.lczf.gov.cn/lczxdw/lcsthjj/fdzdgknr/gzdt/
TRS CMS，单页列表（分页参数无效），20条/页
"""
import os, sys, re, time
import requests
from bs4 import BeautifulSoup
from datetime import datetime, timedelta
from urllib.parse import urljoin

DB_PATH = os.getenv("SEARCH_DB", "/root/search.db")
BASE_URL = "http://xxgk.lczf.gov.cn/lczxdw/lcsthjj/fdzdgknr/gzdt/"
SITE_NAME = "陵川县政府-生态环境局-部门工作"
THRESHOLD = (datetime.now() - timedelta(days=3*365)).strftime("%Y-%m-%d")

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/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",
}
session = requests.Session()
session.headers.update(HEADERS)
session.verify = False
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
import sqlite3

def store_item(title, date_str, content, page_url):
    try:
        conn = sqlite3.connect(DB_PATH, timeout=10)
        c = conn.cursor()
        summary = (content.strip()[:200] if content.strip() else '')
        date_rank = 0
        if date_str:
            try:
                date_rank = int(datetime.strptime(date_str[:10], "%Y-%m-%d").timestamp())
            except:
                pass
        c.execute("""INSERT OR IGNORE INTO gov_raw (title, publish_date, content, page_url, source_url, site_name, summary, date_rank)
                     VALUES (?,?,?,?,?,?,?,?)""",
                  (title.strip(), date_str, content.strip(), page_url.strip(), page_url.strip(), SITE_NAME, summary, date_rank))
        a = c.rowcount; conn.commit(); conn.close(); return a
    except Exception as e:
        print(f"[ERROR] 写入失败: {e}"); return 0

def fetch(url, max_retries=3):
    for i in range(max_retries):
        try:
            r = session.get(url, timeout=15)
            r.encoding = "utf-8"
            if r.status_code == 200:
                return r.text
        except Exception as e:
            print(f"[WARN] {url} 请求失败: {e}")
        if i < max_retries - 1:
            time.sleep(2)
    return None

def parse_list_page(html):
    soup = BeautifulSoup(html, "html.parser")
    items = []
    content_div = soup.find("div", class_=lambda c: c and "zfxxgk_zdgkc" in str(c))
    if not content_div:
        return items
    
    # 每个条目是 a + 日期文本
    for a in content_div.find_all("a", href=True):
        title = a.get_text(strip=True)
        href = a["href"]
        if not title or not href:
            continue
        full_url = urljoin(BASE_URL, href)
        
        # 日期在 <a> 后面的文本中
        parent = a.parent
        if parent:
            all_text = parent.get_text("|", strip=True)
            m = re.search(r'(\d{4}-\d{1,2}-\d{1,2})', all_text)
            date_str = m.group(1) if m else ""
        else:
            date_str = ""
        
        items.append((title, date_str, full_url))
    return items

def parse_detail_page(url):
    html = fetch(url)
    if not html:
        return None, None, None
    soup = BeautifulSoup(html, "html.parser")
    
    # 标题
    title = ""
    h1 = soup.find("h1")
    if h1:
        title = h1.get_text(strip=True)
    if not title:
        t = soup.find("title")
        if t:
            title = t.get_text(strip=True).split("_")[0].strip()
    
    # 日期
    date_str = ""
    page_text = soup.get_text()
    m = re.search(r'发布日期[：:]?\s*(\d{4}-\d{1,2}-\d{1,2})', page_text)
    if m:
        date_str = m.group(1)
    
    # 正文 - 从 div.main 提取 <p> 标签
    content_parts = []
    body = soup.find("div", class_=lambda c: c and "main" in str(c))
    if body:
        for p in body.find_all("p"):
            txt = p.get_text(strip=True)
            if txt and len(txt) > 3:
                skip_words = ["如果内容不能正常显示", "扫一扫", "分享到", "上一篇", "下一篇", "责任编辑", "编辑:"]
                if any(w in txt for w in skip_words):
                    continue
                content_parts.append(txt)
    
    content = "\n\n".join(content_parts)
    
    # 附件
    attachments = []
    if body:
        for a in body.find_all("a", href=True):
            h = a["href"].lower()
            if re.search(r'\.(pdf|doc|docx|xls|xlsx|zip|rar|ppt|pptx)$', h):
                fname = a.get_text(strip=True) or os.path.basename(a["href"])
                full_url = urljoin(url, a["href"])
                attachments.append(f"[{fname}]({full_url})")
    if attachments:
        if content:
            content += "\n\n---\n**附件：**\n" + "\n".join(attachments)
        else:
            content = "\n".join(attachments)
    
    return title, date_str, content

def main():
    print(f"[START] {SITE_NAME} 阈值: {THRESHOLD}")
    total_new = 0
    total_skip = 0
    total_err = 0
    
    html = fetch(BASE_URL)
    if not html:
        print("[ERR] 获取列表页失败")
        return
    
    items = parse_list_page(html)
    print(f"\n[LIST] 共 {len(items)} 条")
    
    for title, date_str, detail_url in items:
        if date_str and date_str < THRESHOLD:
            print(f"  [SKIP] {date_str} {title[:40]}")
            total_skip += 1
            continue
        
        if detail_url.lower().endswith('.pdf'):
            st = store_item(title, date_str or "", f"[查看PDF]({detail_url})", detail_url)
            if st:
                total_new += 1
                print(f"  [PDF] {date_str} {title[:40]}")
            else:
                total_err += 1
            continue
        
        t, d, c = parse_detail_page(detail_url)
        if t and c:
            final_date = d or date_str or ""
            st = store_item(t, final_date, c, detail_url)
            if st:
                total_new += 1
                print(f"  [OK] {final_date} {t[:40]}")
            else:
                total_err += 1
                print(f"  [DUP] {final_date} {t[:40]}")
        else:
            total_err += 1
            print(f"  [ERR] {d or date_str or ''} {title[:40]} 解析失败 {detail_url}")
        time.sleep(0.3)
    
    print(f"\n[DONE] 新增: {total_new}, 跳过: {total_skip}, 失败: {total_err}")

if __name__ == "__main__":
    main()
