#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""改进版正文提取：先 meta，再主内容容器里的段落，最后兜底容器文本。"""
import re


def clean(s):
    s = re.sub(r"<[^>]+>", " ", s)
    s = re.sub(r"\s+", " ", s).strip()
    rep = {"&nbsp;": " ", "&amp;": "&", "&#8217;": "'", "&#039;": "'", "&#39;": "'",
           "&quot;": '"', "&rsquo;": "'", "&#8203;": "", "&ndash;": "–",
           "&mdash;": "—", "&hellip;": "…", "&#8220;": '"', "&#8221;": '"'}
    for k, v in rep.items():
        s = s.replace(k, v)
    return s


BAD = ("cookie", "javascript", "browser", "sign in", "log in", "subscribe",
       "accept all", "privacy policy", "skip to", "opens in a new")


def _container(h):
    for pat in [r'(?is)<main\b[^>]*>(.*?)</main>',
                r'(?is)<article\b[^>]*>(.*?)</article>',
                r'(?is)<div[^>]+id="(?:contentarea|main-content|content|main)"[^>]*>(.*?)</div>\s*</div>']:
        m = re.search(pat, h)
        if m and len(m.group(1)) > 1500:
            return m.group(1)
    return h


def extract2(h):
    if not h:
        return "", "empty"
    m = re.search(r'<meta[^>]+(?:property|name)="(?:og:description|description)"[^>]+content="([^"]{60,1500})"', h, re.I)
    if not m:
        m = re.search(r'content="([^"]{60,1500})"[^>]+(?:property|name)="(?:og:description|description)"', h, re.I)
    if m:
        d = clean(m.group(1))
        if d and not any(b in d.lower() for b in BAD):
            return d, "meta"

    body = _container(h)
    body = re.sub(r"(?is)<(script|style|nav|header|footer|form|svg|noscript|aside)[^>]*>.*?</\1>", " ", body)
    blocks = []
    for p in re.findall(r"(?is)<(p|blockquote)\b[^>]*>(.*?)</\1>", body):
        t = clean(p[1])
        if len(t) >= 90 and not any(b in t.lower() for b in BAD):
            blocks.append(t)
        if len(blocks) >= 3:
            break
    if blocks:
        return " ".join(blocks)[:1400], "body"

    # 兜底：容器纯文本开头（跳过程序性表格噪声）
    t = clean(body)
    t = re.sub(r"\s{2,}", " ", t)
    if len(t) >= 150:
        return t[:900], "container"
    return "", "none"
