#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
益阳市生态环境局 - 环保影响评价 爬虫
CMS: 益阳政府站群自定义CMS
List: /yyshjbhj/3452/3467/default.htm (P1), default_{N-1}.htm (PN)
Detail: /yyshjbhj/3452/3467/content_XXXXXX.html
每页15条
"""

import requests, re, json, sqlite3, time, sys
from bs4 import BeautifulSoup

DB_PATH = "/root/search.db"
SITE_NAME = "益阳市生态环境局-环保影响评价"
CATEGORY = "环保影响评价"
GROUP = "湖南"
BASE_URL = "http://www.yiyang.gov.cn"
LIST_PATH = "/yyshjbhj/3452/3467"
MAX_PAGES = 5

HEADERS = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
    "Accept-Language": "zh-CN,zh;q=0.9",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
}

SKIP_TEXTS = [
    "【打印本页】", "【关闭窗口】", "打印本页", "关闭窗口",
    "转载分享：", "浏览量：", "相关附件：", "相关稿件：",
    "扫一扫在手机打开", "附件：",
]


def decode_resp(r):
    """Handle GB2312 encoding properly using raw bytes."""
    raw = r.content
    # Check Content-Type header first
    ct = r.headers.get("Content-Type", "")
    if "gb2312" in ct.lower() or "gbk" in ct.lower() or "charset=gb" in ct.lower():
        return raw.decode("gbk", errors="replace")
    # Check meta charset in raw bytes
    raw_lower = raw[:2000].lower()
    if b"gb2312" in raw_lower or b"gbk" in raw_lower or b"charset=gb" in raw_lower:
        return raw.decode("gbk", errors="replace")
    # Fallback: try to decode as gbk and check if it's valid
    try:
        sample_gbk = raw[:500].decode("gbk")
        # If no replacement chars, it's valid GBK
        if "\ufffd" not in sample_gbk:
            return raw.decode("gbk", errors="replace")
    except:
        pass
    # Default to utf-8
    return raw.decode("utf-8", errors="replace")


# ---------- Table to Markdown ----------

def table_to_md(table, *args, **kwargs):
    """保留 HTML 表格结构（不转 md）"""
    return str(table)

def render_paragraph(p_tag, detail_url):
    """Render a <p> preserving <a> links and <img> as markdown."""
    parts = []
    for elem in p_tag.contents:
        if isinstance(elem, str):
            t = elem.strip()
            if t:
                parts.append(t)
        elif elem.name == "a":
            href = elem.get("href", "").strip()
            text = elem.get_text(strip=True)
            if href and text:
                full = href if href.startswith("http") else (BASE_URL + href if href.startswith("/") else BASE_URL + "/" + href.lstrip("/"))
                parts.append(f"[{text}]({full})")
            elif text:
                parts.append(text)
        elif elem.name in ("b", "strong", "span", "font"):
            t = elem.get_text(" ", strip=True)
            if t:
                parts.append(t)
        elif elem.name == "img":
            src = elem.get("src", "")
            if src:
                alt = elem.get("alt", "")
                full_src = src if src.startswith("http") else (BASE_URL + src if src.startswith("/") else BASE_URL + "/" + src.lstrip("/"))
                parts.append(f"![{alt}]({full_src})" if alt else f"![]({full_src})")
        elif elem.name == "br":
            parts.append("\n")
        elif hasattr(elem, "get_text"):
            t = elem.get_text(" ", strip=True)
            if t:
                parts.append(t)
    return " ".join(parts)


def extract_content(content_div, detail_url):
    """Extract paragraphs + tables from content div."""
    parts = []
    processed = set()

    for s in content_div.find_all(["script", "style"]):
        s.decompose()

    for child in content_div.children:
        if child.name is None:
            continue
        tn = child.name.lower()

        if tn == "p":
            txt = render_paragraph(child, detail_url)
            if txt:
                parts.append(txt)

        elif tn == "table":
            all_text = child.get_text(strip=True)
            if len(all_text) < 15:
                continue
            md = table_to_md(child)
            if md:
                parts.append(md)

        elif tn == "img":
            src = child.get("src", "")
            if src and id(child) not in processed:
                processed.add(id(child))
                alt = child.get("alt", "")
                full_src = src if src.startswith("http") else (BASE_URL + src if src.startswith("/") else BASE_URL + "/" + src.lstrip("/"))
                parts.append(f"![{alt}]({full_src})" if alt else f"![]({full_src})")

        elif tn in ("div", "section", "center"):
            for sub in child.find_all(["p", "table", "img"], recursive=True):
                if id(sub) in processed:
                    continue
                processed.add(id(sub))
                if sub.name == "p":
                    txt = render_paragraph(sub, detail_url)
                    if txt:
                        parts.append(txt)
                elif sub.name == "table":
                    all_text = sub.get_text(strip=True)
                    if len(all_text) < 15:
                        continue
                    md = table_to_md(sub)
                    if md:
                        parts.append(md)
                elif sub.name == "img":
                    src = sub.get("src", "")
                    if src:
                        alt = sub.get("alt", "")
                        full_src = src if src.startswith("http") else (BASE_URL + src if src.startswith("/") else BASE_URL + "/" + src.lstrip("/"))
                        parts.append(f"![{alt}]({full_src})" if alt else f"![]({full_src})")

        elif tn == "wbr":
            continue

    filtered = []
    for p in parts:
        if any(sk in p for sk in SKIP_TEXTS):
            continue
        if re.match(r'^(来源|发布日期)[：:]\s*', p):
            continue
        filtered.append(p)

    return "\n\n".join(filtered)


# ---------- Attachments ----------

def extract_attachments(soup):
    atts = []
    seen = set()
    for a in soup.find_all("a", href=True):
        href = a["href"]
        if re.search(r"\.(pdf|doc|docx|xls|xlsx|rar|zip|txt)$", href, re.I):
            if href.startswith("/"):
                href = BASE_URL + href
            elif not href.startswith("http"):
                href = BASE_URL + "/" + href.lstrip("/")
            name = a.get_text(strip=True) or href.split("/")[-1].split("?")[0]
            if href not in seen:
                seen.add(href)
                atts.append({"name": name, "url": href})
    return atts


# ---------- Detail ----------

def fetch_detail(url, list_title=""):
    try:
        r = requests.get(url, headers=HEADERS, timeout=20)
        html = decode_resp(r)
    except Exception as e:
        return None, None, None, []

    soup = BeautifulSoup(html, "html.parser")

    # Title: Meta ArticleTitle (most complete)
    title = ""
    mt = soup.find("meta", attrs={"name": "ArticleTitle"})
    if mt and mt.get("content"):
        title = mt["content"].strip()
    if not title:
        # Detail page title div
        dt = soup.find("div", class_="xr-b-title")
        if dt:
            title = dt.get_text(strip=True)
    if not title:
        # list_title fallback
        title = list_title
    if not title:
        title_tag = soup.find("title")
        if title_tag:
            title = title_tag.get_text(strip=True)

    # Date: Meta PubDate
    date_str = ""
    md = soup.find("meta", attrs={"name": "PubDate"})
    if md and md.get("content"):
        date_str = md["content"].strip()[:10]

    # Content
    content_div = soup.find("div", class_="detail-text", id="zoom")
    if not content_div:
        # Fallback: find any content div
        for cls in ["detail-text", "article-content", "content", "text"]:
            content_div = soup.find("div", class_=cls)
            if content_div:
                break

    attachments = extract_attachments(soup)

    if content_div:
        content = extract_content(content_div, url)
    else:
        content = ""

    # Fallback for empty content
    if len(content.strip()) < 20:
        content = f'<p><a href="{url}">{title}</a></p>'
        if attachments:
            for a in attachments:
                content += f"\n\n附件：[{a['name']}]({a['url']})"

    return title, date_str, content, attachments


# ---------- List ----------

def extract_list_page(page_num):
    """Extract articles from page N (1-indexed)."""
    if page_num == 1:
        url = f"{BASE_URL}{LIST_PATH}/default.htm"
    else:
        # 0-indexed: PN -> default_{N-1}.htm
        url = f"{BASE_URL}{LIST_PATH}/default_{page_num - 1}.htm"

    try:
        r = requests.get(url, headers=HEADERS, timeout=20)
        html = decode_resp(r)
    except Exception as e:
        print(f"  Page {page_num} error: {e}")
        return []

    soup = BeautifulSoup(html, "html.parser")

    # Find the article list area
    list_div = soup.find("div", class_="lbcc-nr")
    if not list_div:
        return []

    articles = []
    for ul in list_div.find_all("ul"):
        for li in ul.find_all("li"):
            a = li.find("a")
            if not a:
                continue
            href = a.get("href", "")
            if not href or "content_" not in href:
                continue

            title = a.get("title", "") or a.get_text(strip=True)
            if not title or len(title) < 5:
                continue

            # Full URL
            if href.startswith("/"):
                full_url = BASE_URL + href
            elif href.startswith("http"):
                full_url = href
            else:
                full_url = f"{BASE_URL}{LIST_PATH}/{href}"

            # Date from <span> after <a>
            date_span = li.find("span")
            date = date_span.get_text(strip=True) if date_span else ""

            articles.append((title, full_url, date))

    return articles


# ---------- DB ----------

def init_db():
    conn = sqlite3.connect(DB_PATH, timeout=60)
    conn.execute("PRAGMA journal_mode=WAL")
    conn.execute("PRAGMA busy_timeout=5000")
    return conn


def save_article(conn, title, page_url, publish_date, content, attachments):
    summary = content[:200] if content else title
    summary = re.sub(r"\s+", " ", summary).strip()
    att_json = json.dumps(attachments, ensure_ascii=False) if attachments else "[]"
    for attempt in range(3):
        try:
            cur = conn.execute(
                """INSERT OR IGNORE INTO gov_raw
                   (site_name, source_url, page_url, title, publish_date, summary, content, category, attachments, group_name)
                   VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
                (SITE_NAME, page_url, page_url, title.strip(), publish_date,
                 summary, content, CATEGORY, att_json, GROUP),
            )
            conn.commit()
            return cur.rowcount > 0
        except sqlite3.OperationalError as e:
            if "locked" in str(e) and attempt < 2:
                time.sleep(2)
                continue
            print(f"  DB error: {e}", file=sys.stderr)
            return False
    return False


# ---------- Main ----------

def main():
    max_pages = MAX_PAGES
    if len(sys.argv) > 1:
        try:
            max_pages = int(sys.argv[1])
        except ValueError:
            if sys.argv[1] in ("--max-pages",):
                if len(sys.argv) > 2:
                    try:
                        max_pages = int(sys.argv[2])
                    except ValueError:
                        pass

    print(f"Scraping {SITE_NAME}, max pages: {max_pages}")

    conn = init_db()
    total_new = 0
    total_found = 0

    for pn in range(1, max_pages + 1):
        articles = extract_list_page(pn)
        if not articles:
            print(f"  Page {pn}: 0 articles (end)")
            break

        total_found += len(articles)

        for title, page_url, date in articles:
            # Skip very old
            if date and date < "2020-01-01":
                continue

            # Check if already exists
            cur = conn.execute("SELECT id FROM gov_raw WHERE page_url = ?", (page_url,))
            if cur.fetchone():
                continue

            det_title, det_date, det_content, det_atts = fetch_detail(page_url, title)
            final_title = det_title or title
            final_date = det_date or date
            final_content = det_content or f"[{final_title}]({page_url})"
            final_atts = det_atts or []

            if save_article(conn, final_title, page_url, final_date, final_content, final_atts):
                total_new += 1

            time.sleep(0.3)

        print(f"  Page {pn}: {len(articles)} found, {total_new} new so far")

    conn.commit()
    conn.close()
    print(f"\nDone! Total found: {total_found}, New: {total_new}")


if __name__ == "__main__":
    main()
