#!/usr/bin/env python3
"""乐山市五通桥区人民政府-重大项目"""
import re, sys, os, json, time, requests
from bs4 import BeautifulSoup

DB_PATH = os.environ.get("DB_PATH", "/root/search.db")
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": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
    "Accept-Language": "zh-CN,zh;q=0.9",
}
SITE_NAME = "乐山市五通桥区人民政府-重大项目"
GROUP = "四川乐山"
MAX_PAGES = 1  # single page, 35 items
BASE_URL = "http://www.wtq.gov.cn"
LIST_URL = "http://www.wtq.gov.cn/wtqq/zdxmwtq/xxlist.shtml"

def fetch(url, encoding="utf-8"):
    r = requests.get(url, headers=HEADERS, timeout=30, allow_redirects=True)
    r.encoding = encoding
    return r.text

def resolve_url(rel_url):
    if rel_url.startswith("http"):
        return rel_url
    rel = rel_url.lstrip("./")
    if rel.startswith("wtqq"):
        return "http://www.wtq.gov.cn/" + rel
    return "http://www.wtq.gov.cn/wtqq/zdxmwtq/" + rel

def extract_list(html):
    """Extract (title, url, date) from list page"""
    items = []
    soup = BeautifulSoup(html, 'html.parser')
    tables = soup.find_all('table')
    if len(tables) < 6:
        print("ERROR: expected at least 6 tables, found {}".format(len(tables)))
        return items

    table = tables[5]  # 6th table is the content list
    rows = table.find_all('tr')

    # Row 0 is the merged summary, skip it. Rows 1+ have item pairs.
    for tr in rows[1:]:
        cells = tr.find_all(['td', 'th'])
        if len(cells) < 2:
            continue
        cell0 = cells[0]
        a = cell0.find('a')
        if not a:
            continue
        title = a.get_text(strip=True)
        href = a.get('href', '').strip()
        if not title or not href:
            continue

        # Date is in cell 1
        date = cells[1].get_text(strip=True)
        date = re.sub(r'\s+', '', date)
        # Validate date format
        if not re.match(r'\d{4}-\d{1,2}-\d{1,2}', date):
            # Try to extract from URL
            dm = re.search(r'(\d{4})(\d{2})/', href)
            if dm:
                year, month = dm.group(1), dm.group(2)
                date = year + "-" + month + "-01"
            else:
                date = ""
        items.append((title, href, date))
    return items

def extract_detail(html):
    """Extract body content from detail page"""
    soup = BeautifulSoup(html, 'html.parser')

    # Title from <ucaptitle> tag
    title = ""
    uc = soup.find('ucaptitle')
    if uc:
        title = uc.get_text(strip=True)

    # Date from <publishtime> tag
    date = ""
    pt = soup.find('publishtime')
    if pt:
        dm = re.search(r'(\d{4}-\d{1,2}-\d{1,2})', pt.get_text())
        if dm:
            date = dm.group(1)
    if not date:
        dm = re.search(r'(\d{4}-\d{1,2}-\d{1,2})', html[:2000])
        if dm:
            date = dm.group(1)

    # Body from #articleContent
    body = ""
    el = soup.find(id='articleContent')
    if not el:
        el = soup.find(id='MyContent') or soup.find(id='news-content')
    if el:
        parts = []
        for child in el.find_all(['p', 'table']):
            if child.name == 'table':
                parts.append(str(child))
            else:
                txt = child.get_text(strip=True)
                if txt:
                    parts.append(txt)
        body = '\n\n'.join(parts)

    return title, body, date

def save_to_db(items, site_name, group):
    import sqlite3
    conn = sqlite3.connect(DB_PATH, timeout=60)
    c = conn.cursor()
    inserted = 0
    for title, url, date, body in items:
        try:
            c.execute("""INSERT OR REPLACE INTO gov_raw
                (page_url, site_name, group_name, title, publish_date, summary, content)
                VALUES (?, ?, ?, ?, ?, ?, ?)""",
                (url, site_name, group, title, date, body, body))
            inserted += 1
        except Exception as e:
            print("DB error: {} - {}".format(url, e))
    conn.commit()
    conn.close()
    return inserted

def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--max-pages', type=int, default=MAX_PAGES)
    args = parser.parse_args()

    all_items = []
    html = fetch(LIST_URL)
    items = extract_list(html)
    all_items.extend(items)
    print("Page 1: {} items".format(len(items)))

    print("\nTotal list items: {}".format(len(all_items)))

    # Fetch details
    detail_items = []
    failed = 0
    for i, (title, rel_url, date) in enumerate(all_items):
        url = resolve_url(rel_url)
        try:
            html = fetch(url)
            d_title, body, d_date = extract_detail(html)
            if not d_date:
                d_date = date
            if not d_title:
                d_title = title
            detail_items.append((d_title, url, d_date, body))
            if (i + 1) % 10 == 0:
                print("  progress: {}/{}".format(i + 1, len(all_items)))
        except Exception as e:
            print("  FAILED: {} - {}".format(url, e))
            failed += 1
        time.sleep(0.3)

    print("\nDetails fetched: {}, failed: {}".format(len(detail_items), failed))

    # Save to DB
    inserted = save_to_db(detail_items, SITE_NAME, GROUP)
    print("Inserted: {}".format(inserted))

    # Summary
    print("\n=== Summary ===")
    print("{} | {} | {} | {} | {}".format(SITE_NAME, inserted, 0, failed, 0))

if __name__ == "__main__":
    main()
