#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
导出搜狐博客全部博文（只读，不修改博客任何设置）
博客：normanli.blog.sohu.com（飞扬寻梦）
已知：118 篇，其中 86 公开、32 隐藏。
隐藏篇在列表页不暴露 URL，只能走管理后台拿链接，脚本会尽力尝试。

用法：
1. 安装依赖：pip install selenium beautifulsoup4 html2text requests
2. 启动 Chrome（调试模式，继承你已登录的搜狐账号）：
   start chrome --remote-debugging-port=9222
   在 Chrome 里确认搜狐博客是登录状态（能打开 normanli.blog.sohu.com）
3. 运行：python export_sohu_blog.py  （Chrome 保持开着，不用关）
4. 结果在脚本同目录的 sohu_blog_export/ 下：
   每篇一个 .md（含标题/日期/原文链接/是否隐藏）+ images/ 图片 + index.md 索引 + report.txt 盘点报告

注意：搜狐服务器偶尔抽风（文章页 ERR_EMPTY_RESPONSE、管理后台 514），
脚本自带 3 次重试；实在抓不到的会记在 report.txt 的失败清单里，晚点重跑即可。
"""

import os
import re
import time
from urllib.parse import urljoin, urlparse

import requests
from bs4 import BeautifulSoup

try:
    import html2text
    HAVE_H2T = True
except ImportError:
    HAVE_H2T = False

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By

BLOG = "https://normanli.blog.sohu.com"
ENTRY = BLOG + "/entry/"
# 管理后台：隐藏文章的 URL 只能从这里拿到（搜狐经常 514，尽力而为）
MANAGE_URLS = [
    "https://blog.sohu.com/manage/entry.do?m=list",
    "https://blog.sohu.com/manage/entry.do",
    "https://blog.sohu.com/manage/entry.do?m=add&t=index",
]
OUTDIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "sohu_blog_export")
IMGDIR = os.path.join(OUTDIR, "images")
ARTICLE_RE = re.compile(r"normanli\.blog\.sohu\.com/(\d+)\.html")
DATE_RE = re.compile(r"20\d{2}[-/]\d{1,2}[-/]\d{1,2}(?:\s+\d{1,2}:\d{2})?")
# 正文容器候选（搜狐老模板），按顺序试，兜底用“文本量最大的 div”
CONTENT_SELECTORS = [
    "#articleContent", ".article-content", "#content", ".blog_content",
    "#mainContent", ".entry-content", "#article_body", ".articleBody",
]

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


def make_driver():
    opts = Options()
    opts.add_argument("--disable-blink-features=AutomationControlled")
    # 接管已启动的 Chrome（先用 --remote-debugging-port=9222 把 Chrome 跑起来，
    # 登录态直接继承；Chrome 保持开着就行，不锁 profile）
    opts.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
    # chromedriver 兜底：脚本同目录下放了 chromedriver.exe 就直接用，
    # 跳过 Selenium Manager 在线下载（googlechromelabs.github.io 在国内可能连不上）
    local_driver = os.path.join(os.path.dirname(os.path.abspath(__file__)), "chromedriver.exe")
    if os.path.isfile(local_driver):
        driver = webdriver.Chrome(options=opts, service=Service(executable_path=local_driver))
    else:
        driver = webdriver.Chrome(options=opts)
    driver.set_page_load_timeout(40)
    return driver


def get_with_retry(driver, url, tries=3):
    last = None
    for i in range(tries):
        try:
            driver.get(url)
            time.sleep(1.5)
            if driver.page_source and len(driver.page_source) > 5000:
                return True
            last = f"页面过短({len(driver.page_source or '')}字节)"
        except Exception as e:  # noqa: BLE001 - 超时/空响应都重试
            last = repr(e)
            time.sleep(3)
    print(f"  [失败] {url} -> {last}")
    return False


def crawl_list_pages(driver):
    """走 6 页列表，收集 (id, 标题, 日期, 是否隐藏)。"""
    posts = {}   # id -> dict
    hidden_count = 0
    if not get_with_retry(driver, ENTRY):
        raise SystemExit("列表页打不开，先确认 Chrome 里搜狐博客是登录状态。")
    for page in range(1, 7):
        if page > 1:
            # 翻页是 JS：chageEntryPage(n)
            try:
                driver.execute_script(f"chageEntryPage({page})")
            except Exception:  # noqa: BLE001
                pass
            time.sleep(2)
        soup = BeautifulSoup(driver.page_source, "html.parser")
        # 公开文章：找 /<id>.html 链接
        for a in soup.find_all("a", href=True):
            m = ARTICLE_RE.search(a["href"])
            if not m:
                continue
            pid = m.group(1)
            title = a.get_text(strip=True)
            if not title or pid in posts:
                continue
            # 日期一般在链接附近，往上找包含日期的文本
            date = ""
            parent_text = a.parent.get_text(" ", strip=True) if a.parent else ""
            dm = DATE_RE.search(parent_text)
            if dm:
                date = dm.group(0)
            posts[pid] = {"id": pid, "title": title, "date": date,
                          "url": f"{BLOG}/{pid}.html", "hidden": False}
        # 隐藏文章：列表里只显示“该日志已隐藏”，不暴露 URL，计数即可
        n_hidden = len(soup.find_all(string=re.compile(r"该日志已隐藏")))
        hidden_count += n_hidden
        print(f"第 {page} 页：累计文章 {len(posts)} 篇，隐藏标记 {n_hidden} 处")
        time.sleep(1)
    return posts, hidden_count


def crawl_manage_backend(driver, posts):
    """尽力从管理后台拿到隐藏文章的 URL。"""
    found = 0
    for url in MANAGE_URLS:
        print(f"尝试管理后台：{url}")
        if not get_with_retry(driver, url, tries=2):
            continue
        if "514" in (driver.title or "") or "ERROR" in (driver.title or ""):
            print("  管理后台报 514，跳过")
            continue
        soup = BeautifulSoup(driver.page_source, "html.parser")
        for a in soup.find_all("a", href=True):
            m = ARTICLE_RE.search(urljoin(BLOG, a["href"]))
            if not m:
                continue
            pid = m.group(1)
            if pid not in posts:
                title = a.get_text(strip=True) or f"(隐藏文章 {pid})"
                posts[pid] = {"id": pid, "title": title, "date": "",
                              "url": f"{BLOG}/{pid}.html", "hidden": True}
                found += 1
        if found:
            break
    print(f"管理后台找到隐藏文章 {found} 篇")
    return found


def pick_content(soup):
    for sel in CONTENT_SELECTORS:
        el = soup.select_one(sel)
        if el and len(el.get_text(strip=True)) > 200:
            return el
    # 兜底：文本量最大的 div（排除脚本样式）
    best, best_len = None, 0
    for div in soup.find_all("div"):
        t = div.get_text(strip=True)
        if len(t) > best_len and len(t) < 200000:
            best, best_len = div, len(t)
    return best


def download_image(session, src, pid, idx):
    try:
        r = session.get(src, headers=HEADERS, timeout=20)
        r.raise_for_status()
        ext = os.path.splitext(urlparse(src).path)[1].lower()[:5] or ".jpg"
        if ext not in (".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"):
            ext = ".jpg"
        name = f"{pid}_{idx}{ext}"
        with open(os.path.join(IMGDIR, name), "wb") as f:
            f.write(r.content)
        return "images/" + name
    except Exception as e:  # noqa: BLE001
        print(f"    图片下载失败 {src}: {e}")
        return None


def export_article(driver, session, post):
    pid = post["id"]
    if not get_with_retry(driver, post["url"]):
        return False, "打开失败"
    soup = BeautifulSoup(driver.page_source, "html.parser")
    for tag in soup(["script", "style", "noscript", "iframe"]):
        tag.decompose()

    # 标题
    title = post["title"]
    h1 = soup.find("h1")
    if h1 and h1.get_text(strip=True):
        title = h1.get_text(strip=True)

    # 日期
    date = post["date"]
    if not date:
        m = DATE_RE.search(soup.get_text(" ", strip=True)[:3000])
        if m:
            date = m.group(0)

    # 正文
    content = pick_content(soup)
    if not content or len(content.get_text(strip=True)) < 50:
        return False, "正文提取失败(页面结构异常)"

    # 图片本地化
    idx = 0
    for img in content.find_all("img"):
        src = img.get("src") or img.get("data-src") or ""
        if not src or src.startswith("data:"):
            continue
        src = urljoin(post["url"], src)
        idx += 1
        local = download_image(session, src, pid, idx)
        if local:
            img["src"] = local
            img.attrs.pop("data-src", None)
            img.attrs.pop("srcset", None)

    # 转 Markdown
    if HAVE_H2T:
        h = html2text.HTML2Text()
        h.body_width = 0
        body = h.handle(str(content))
    else:
        body = content.get_text("\n", strip=True)

    safe_title = re.sub(r'[\\/:*?"<>|]', "_", title)[:60]
    fname = f"{date.replace('/', '-').replace(' ', '_') if date else 'nodate'}_{pid}_{safe_title}.md"
    header = (f"---\ntitle: {title}\ndate: {date}\nurl: {post['url']}\n"
              f"hidden: {post['hidden']}\n---\n\n# {title}\n\n")
    with open(os.path.join(OUTDIR, fname), "w", encoding="utf-8") as f:
        f.write(header + body)
    return True, fname


def main():
    os.makedirs(IMGDIR, exist_ok=True)
    session = requests.Session()
    driver = make_driver()
    try:
        print("== 第 1 步：抓列表页 ==")
        posts, hidden_marks = crawl_list_pages(driver)
        print(f"列表页共 {len(posts)} 篇带链接，隐藏标记 {hidden_marks} 处")

        print("== 第 2 步：管理后台找隐藏文章 ==")
        crawl_manage_backend(driver, posts)
        print(f"合计待导出 {len(posts)} 篇")

        print("== 第 3 步：逐篇导出 ==")
        ok, fail = [], []
        for i, pid in enumerate(sorted(posts), 1):
            post = posts[pid]
            print(f"[{i}/{len(posts)}] {post['date']} {post['title'][:30]}")
            good, info = export_article(driver, session, post)
            (ok if good else fail).append((pid, post["title"], info))
            time.sleep(1.2)

        # 索引 + 报告
        with open(os.path.join(OUTDIR, "index.md"), "w", encoding="utf-8") as f:
            f.write("# 飞扬寻梦 - 搜狐博客导出索引\n\n")
            for pid, title, fname in sorted(ok):
                f.write(f"- [{title}]({fname})\n")
        with open(os.path.join(OUTDIR, "report.txt"), "w", encoding="utf-8") as f:
            f.write(f"列表页带链接文章: {len(posts)} 篇\n")
            f.write(f"列表页隐藏标记: {hidden_marks} 处\n")
            f.write(f"成功导出: {len(ok)} 篇\n")
            f.write(f"失败: {len(fail)} 篇\n")
            for pid, title, info in fail:
                f.write(f"  FAIL {pid} {title} : {info}\n")
        print(f"\n完成：成功 {len(ok)}，失败 {len(fail)}。详见 {OUTDIR}/report.txt")
    finally:
        driver.quit()


if __name__ == "__main__":
    main()
