#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
贵港市生态环境局 - 环评公众参与公示 (sthj.gxgg.gov.cn)
CMS: 自定义PHP CMS (fenye.js + createPageHTML)
列表: index.shtml / index_{N}.shtml (N=2~4, 30条/页, 共4页~94条)
详情: ./t{N}.shtml
详情容器: div.article-con
附件容器: div#article-file
网络: IP 221.7.196.145 + Host header
"""

import sys, os, re, time, json
from datetime import datetime, timezone, timedelta

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from crawler_lib import push_to_searchdb

import requests
from bs4 import BeautifulSoup

# === 自动页数控制 ===
_MAX_PG = None
for i, a in enumerate(sys.argv):
    if a == '--pages' and i + 1 < len(sys.argv):
        _MAX_PG = int(sys.argv[i + 1])
        break
if _MAX_PG is not None:
    print("[AutoPg] max_pages=" + str(_MAX_PG))

SITE_NAME = "贵港市生态环境局-环评公众参与公示"
BASE_IP = "221.7.196.145"
DOMAIN = "sthj.gxgg.gov.cn"
BASE_URL = f"http://{BASE_IP}"
LIST_DIR = "/zfxxgkzl/zfxxgk/hjpj/hpgzcygs"
TOTAL_PAGES = 3  # page 4 is empty
CUTOFF = (datetime.now(timezone.utc) - timedelta(days=365*3)).strftime("%Y-%m-%d")

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
    "Host": DOMAIN,
}

def html_table_to_html(table, base_url=""):
    """保留 HTML 表格结构，仅将相对链接/图片转绝对 URL"""
    import urllib.parse
    tbl = BeautifulSoup(str(table), 'html.parser')
    for a in tbl.find_all('a'):
        href = a.get('href', '')
        if href and not href.startswith(('http', 'javascript', '#')):
            a['href'] = urllib.parse.urljoin(base_url, href) if base_url else href
    for img in tbl.find_all('img'):
        src = img.get('src', '')
        if src and not src.startswith(('http', '//', 'data:')):
            img['src'] = urllib.parse.urljoin(base_url, src) if base_url else src
    return str(tbl)
def fetch(url, timeout=20):
    for attempt in range(3):
        try:
            r = requests.get(url, headers=HEADERS, timeout=timeout, verify=False)
            r.encoding = "utf-8"
            return r.text
        except Exception as e:
            if attempt < 2:
                time.sleep(2)
            else:
                print(f"  [WARN] {url}: {e}")
                return None

def make_list_url(page):
    if page == 1:
        return BASE_URL + LIST_DIR + "/index.shtml"
    return BASE_URL + LIST_DIR + f"/index_{page}.shtml"

def parse_list_page(html):
    """解析列表页：<li><span>date</span><a href="./tN.shtml" title="title">title</a></li>"""
    items = []
    for m in re.finditer(
        r'<li><span>(\d{4}-\d{2}-\d{2})</span><a href="(\./t\d+\.shtml)"[^>]*title="([^"]*)"[^>]*>',
        html, re.DOTALL
    ):
        date = m.group(1).strip()
        href = m.group(2).strip()
        title = m.group(3).strip()
        
        # 解析相对路径为完整URL
        if href.startswith("./"):
            href = "http://" + DOMAIN + LIST_DIR + "/" + href[2:]
        elif href.startswith("/"):
            href = "http://" + DOMAIN + href
        elif not href.startswith("http"):
            href = "http://" + DOMAIN + LIST_DIR + "/" + href
        
        if title and href:
            items.append((title, href, date))
    
    return items

def _clean_span_spaces(text):
    """清除中文字符间的span碎片空格"""
    text = re.sub(r'(?<=[\u4e00-\u9fff])[ \t\u3000]+(?=[\u4e00-\u9fff])', '', text)
    text = re.sub(r'(?<=[\u4e00-\u9fff])[ \t\u3000]+(?=\d)', '', text)
    text = re.sub(r'(?<=\d)[ \t\u3000]+(?=[\u4e00-\u9fff])', '', text)
    text = re.sub(r'\s+([，。、；：？！)】」》])', r'\1', text)
    text = re.sub(r'([（【「《])\s+', r'\1', text)
    text = re.sub(r'(?<=\d)\s+(?=\d)', '', text)
    text = re.sub(r'&#\d+;', '', text)
    return re.sub(r'\s+', ' ', text).strip()

def resolve_url(base_url, src):
    """解析相对URL (基于.shtml文件目录)"""
    if src.startswith("http"):
        return src
    if src.startswith("/"):
        return "http://" + DOMAIN + src
    if src.startswith("./"):
        src = src[2:]
    # 相对于.shtml文件目录
    base_dir = base_url.rsplit("/", 1)[0]
    return base_dir + "/" + src

def extract_content(detail_div, page_url):
    """从 div.article-con 提取正文 (含 TRS_EDITOR 嵌套)"""
    # TRS_EDITOR 嵌套：实际内容在 div.trs_editor_view 或 div.view 内部
    editor = detail_div.find("div", class_="trs_editor_view")
    if not editor:
        editor = detail_div.find("div", class_="view")
    if editor:
        content_div = editor
    else:
        content_div = detail_div
    
    parts = []
    
    for child in content_div.children:
        name = getattr(child, 'name', None)
        if not name:
            continue
        
        if name == 'table':
            tbl_html = html_table_to_html(child, page_url)
            if tbl_html:
                parts.append(tbl_html)
        elif name == 'p':
            if child.find_parent("table"):
                continue
            
            # 图片
            for img in child.find_all("img"):
                src = img.get("src", "")
                alt = img.get("alt", "")
                if src:
                    full_src = resolve_url(page_url, src)
                    parts.append(f"![{alt}]({full_src})\n\n")
            
            # 附件链接(正文内)
            for a_tag in child.find_all("a", href=True):
                href = a_tag["href"]
                ext = href.lower().rsplit(".", 1)[-1] if "." in href else ""
                if ext in ('pdf', 'doc', 'docx', 'xls', 'xlsx', 'zip', 'rar', 'ppt', 'pptx'):
                    a_text = a_tag.get_text(" ", strip=True)
                    full_href = resolve_url(page_url, href)
                    if a_text:
                        parts.append(f"[{a_text}]({full_href})\n\n")
            
            # 正文文本
            txt = child.get_text(" ", strip=True)
            txt = _clean_span_spaces(txt)
            if txt and len(txt) > 3:
                parts.append(txt)
                parts.append("\n\n")
        
        elif name == 'img':
            src = child.get("src", "")
            alt = child.get("alt", "")
            if src:
                full_src = resolve_url(page_url, src)
                parts.append(f"![{alt}]({full_src})\n\n")
    
    result = ''.join(parts).strip()
    result = re.sub(r'\n{4,}', '\n\n', result)
    
    # 处理 div.downloadfile 附件（在 article-con 内）
    for df in detail_div.find_all("div", class_="downloadfile"):
        for a in df.find_all("a", href=True):
            a_text = a.get_text(" ", strip=True)
            full_href = resolve_url(page_url, a["href"])
            if a_text and a_text.strip():
                link = f"[{a_text.strip()}]({full_href})"
                if link not in result:
                    result += "\n\n" + link
    
    return result

def parse_detail(url):
    """抓取详情页，返回 (title, content, date)"""
    html = fetch(url)
    if not html:
        return None, None, None
    
    soup = BeautifulSoup(html, "html.parser")
    
    # 标题
    title = ""
    meta = soup.find("meta", attrs={"name": "ArticleTitle"})
    if meta:
        title = meta.get("content", "").strip()
    if not title:
        h1 = soup.find("h1")
        title = h1.get_text(strip=True) if h1 else ""
    if not title:
        tag = soup.find("title")
        if tag:
            t = tag.get_text(strip=True)
            # 清理 "标题 - 栏目 - 站点"
            t = re.sub(r'\s*[-–—|]\s*环评公众参与公示.*', '', t).strip()
            if t and len(t) > 5:
                title = t
    
    # 日期
    date = ""
    meta_d = soup.find("meta", attrs={"name": "PubDate"})
    if meta_d:
        d = meta_d.get("content", "")
        m = re.search(r'(\d{4}-\d{2}-\d{2})', d)
        if m:
            date = m.group(1)
    
    # 正文
    content = ""
    detail_div = soup.find("div", class_="article-con")
    if detail_div:
        content = extract_content(detail_div, url)
    
    # 附件 (article-file)
    attachments = []
    af = soup.find("div", id="article-file")
    if af:
        attachments = []
        for a_tag in af.find_all("a", href=True):
            href = a_tag["href"]
            a_text = a_tag.get_text(" ", strip=True)
            full_href = resolve_url(url, href)
            attachments.append(f"[{a_text}]({full_href})")
        if attachments:
            # 追加到正文末尾
            if content:
                content += "\n\n"
            content += "\n\n".join(attachments)
    
    return title, content, date

def main():
    pages_to_fetch = min(TOTAL_PAGES, _MAX_PG) if _MAX_PG else TOTAL_PAGES
    
    print(f"=== {SITE_NAME} ===")
    print(f"  总页数: {TOTAL_PAGES}, 本次: {pages_to_fetch}")
    
    all_items = []
    for page in range(1, pages_to_fetch + 1):
        list_url = make_list_url(page)
        print(f"  第 {page}/{pages_to_fetch} 页: {list_url}")
        
        html = fetch(list_url)
        if not html:
            print(f"    无法获取, 停止")
            break
        
        items = parse_list_page(html)
        if not items:
            print(f"    空列表, 停止")
            break
        
        print(f"    找到 {len(items)} 条")
        all_items.extend(items)
        time.sleep(0.3)
    
    print(f"\n  列表总计: {len(all_items)} 条\n")
    
    if not all_items:
        print("  无数据")
        return
    
    results = []
    for idx, (title, url, date) in enumerate(all_items):
        print(f"  [{idx+1}/{len(all_items)}] {title[:40]}...", end=" ", flush=True)
        
        dt, content, dd = parse_detail(url)
        final_title = dt or title
        final_date = date or dd
        
        if not content or len(content.strip()) < 10:
            print("⚠ 空")
            # PDF-only页留空
            continue
        
        summary = re.sub(r'<[^>]+>', '', content)[:200].strip()
        if not summary:
            summary = final_title[:200]
        
        results.append({
            "site_name": SITE_NAME,
            "title": final_title,
            "url": url,
            "content": content,
            "summary": summary,
            "pub_date": final_date,
        })
        print(f"✅ ({len(content)}字)")
        
        if (idx + 1) % 20 == 0:
            print(f"  进度: {idx+1}/{len(all_items)}, 已入库: {len(results)}")
    
    if results:
        print(f"\n  入库 {len(results)} 条")
        push_to_searchdb(results, "guigang_hpcygs")
    
    print("完成")


if __name__ == "__main__":
    main()
