#!/usr/bin/env python3
"""韶山市人民政府 — 政务公开（高新技术产业开发区）
http://www.shaoshan.gov.cn/12365/12370/index.htm
政府网站群系统，分页 index_N.htm
"""
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://www.shaoshan.gov.cn/12365/12370/index.htm"
SITE_NAME = "韶山市人民政府-高新区政务公开"
THRESHOLD = (datetime.now() - timedelta(days=3*365)).strftime("%Y-%m-%d")
MAX_PAGES = 5

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 _drop_container_parts(parts):
    """剔除「容器段」：find_all(['p','div']) 会同时收下容器 <div> 与它内部的 <p>，
    导致同一内容重复（容器那份常还被 get_text(strip=True) 拍平）。
    判据：某段被列表内另一段完全包含 → 它是容器段 → 剔除。
    保护：剔除后为空则原样返回。
    """
    if not parts:
        return parts
    ps = [p for p in parts if isinstance(p, str)]
    if len(ps) != len(parts):
        return parts
    # ① 先按值去重 —— 否则两段完全相同时 a in b 与 b in a 双向成立，
    #    会把两段都判成「容器段」剔光，再触发下面的保护而原样返回（等于没修）。
    seen, uniq = set(), []
    for p in parts:
        if p not in seen:
            seen.add(p); uniq.append(p)
    # ② 再剔容器段（被其它段完全包含的那个）
    keep = [a for a in uniq
            if not (len(a) >= 40 and any(b is not a and b and b in a for b in uniq))]
    return keep if keep else uniq


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)
            enc = "gbk"
            m = re.search(rb'charset=([a-zA-Z0-9_-]+)', r.content[:2000])
            if m:
                enc = m.group(1).decode()
            r.encoding = enc
            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, base_url):
    soup = BeautifulSoup(html, "html.parser")
    items = []
    wrap = soup.find("div", class_="wrap-con")
    if not wrap:
        return items
    tables = wrap.find_all("table")
    if not tables:
        return items
    rows = tables[0].find_all("tr")
    for row in rows[1:]:
        cols = row.find_all("td")
        if len(cols) < 3:
            continue
        a = cols[1].find("a", href=True)
        if not a:
            continue
        title = a.get_text(strip=True)
        href = a["href"]
        date_str = cols[2].get_text(strip=True)
        if not title or not href:
            continue
        items.append((title, date_str, urljoin(base_url, href)))
    return items

def parse_detail_page(url):
    html = fetch(url)
    if not html:
        return None, None, None
    soup = BeautifulSoup(html, "html.parser")
    
    title = ""
    h2 = soup.find("h2")
    if h2:
        title = h2.get_text(strip=True)
    if not title:
        t = soup.find("title")
        if t:
            title = t.get_text(strip=True)
            for suffix in ["-政务公开-韶山市人民政府", "-韶山市人民政府", "_韶山市人民政府"]:
                if suffix in title:
                    title = title.split(suffix)[0].strip()
                    break
    
    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).replace('年', '-').replace('月', '-').replace('日', '')
    
    content_parts = []
    xl = soup.find("div", class_="xl-xqnr")
    if xl:
        for tag in list(xl.find_all(["script", "style", "canvas"])):
            tag.decompose()
        for d in list(xl.find_all("div")):
            if not hasattr(d, 'attrs') or d.attrs is None:
                continue
            if d.get("id") in ["div_div", "qr_container"]:
                d.decompose()
        for p in xl.find_all(["p", "div", "span"]):
            if not hasattr(p, 'get_text'):
                continue
            txt = p.get_text(strip=True)
            if txt and len(txt) > 4:
                if "相关解读" in txt or "扫一扫" in txt or "匿名评论" in txt:
                    continue
                if "提交留言" in txt or "验证码" in txt:
                    continue
                content_parts.append(txt)
        for iframe in xl.find_all("iframe", src=True):
            src = iframe["src"]
            if src.lower().endswith(".pdf"):
                content_parts.append(f"[查看PDF附件]({urljoin(url, src)})")
    
    content_parts = _drop_container_parts(content_parts)
    content = "\n\n".join(content_parts)
    
    attachments = []
    for a in soup.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] 韶山市人民政府 阈值: {THRESHOLD} 最多{MAX_PAGES}页")
    total_new = 0
    total_skip = 0
    total_err = 0
    
    for pg in range(1, MAX_PAGES + 1):
        page_url = BASE_URL if pg == 1 else f"http://www.shaoshan.gov.cn/12365/12370/index_{pg-1}.htm"
        print(f"\n[PAGE] 第{pg}页: {page_url}")
        html = fetch(page_url)
        if not html:
            print(f"  [ERR] 获取失败")
            continue
        
        items = parse_list_page(html, page_url)
        if not items:
            print(f"  [WARN] 无条目")
            continue
        
        for title, date_str, detail_url in items:
            if date_str < THRESHOLD:
                print(f"  [SKIP] {date_str} {title[:40]}")
                total_skip += 1
                continue
            t, d, c = parse_detail_page(detail_url)
            if t and c:
                st = store_item(t, d or date_str, c, detail_url)
                if st:
                    total_new += 1
                    print(f"  [OK] {d or date_str} {t[:40]}")
                else:
                    total_err += 1
                    print(f"  [DUP] {d or date_str} {t[:40]}")
            else:
                total_err += 1
                print(f"  [ERR] {d or date_str} {title[:40]} 详情页解析失败 {detail_url}")
            time.sleep(0.3)
        time.sleep(0.5)
    
    print(f"\n[DONE] 新增: {total_new}, 跳过: {total_skip}, 失败: {total_err}")

if __name__ == "__main__":
    main()
