#!/usr/bin/env python3
"""
磁链聚合搜索 · 网页版 (BTSOU-Web)
==================================
对 BTSOU_Plus 的功能重写：多源并行检索 + 归一化 + 去重 + 筛选排序 + 导出。

与原程序的口径对齐（2026-10-14 补）：
  * 源清单＝原版作者下发的 ResPool.txt（全量 28 源），由 tools/gen_sources.py 生成 sources.json
  * 逐源出站策略＝原版 ResPool 的『代理(Acting)』列：direct / vpn / auto（先直连，失败走本机 VPN）
  * 关键词编码＝原版 ResPool 的『编码方式』列：UrlEncode / Base64UrlSafe / Hex
  * 列表页切块＝原版 ResPool 的『分割符』列（literal split，与原版一致）
  * 字段提取＝原版内嵌的『通用正则组』（多候选依次回退），源可用 field 级正则覆盖
  * 详情页补磁链＝原版对无磁链列表页会抓详情页（本版做成可开关 + 缓存 + 限流）

安全设计（与审计报告一致，保持不变）：
  * 无遥测、无错误堆栈上报、无机器指纹采集、无实名举报、无订阅分发
  * 无自动更新；源清单在本机 sources.json，可审计
  * 出站只有两种：直连，或走你自己在本机跑的代理（默认 127.0.0.1:10809），不经任何第三方

仅依赖 Python 3 标准库；二维码为可选增强（装了 qrcode 才启用）。
"""
from __future__ import annotations

import base64
import gzip
import html as _html
import json
import os
import re
import subprocess
import sys
import tempfile
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
from concurrent.futures import ThreadPoolExecutor, as_completed
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

APP_DIR = os.path.dirname(os.path.abspath(__file__))
WEB_DIR = os.path.join(APP_DIR, "web")
SOURCES_FILE = os.path.join(APP_DIR, "sources.json")

HOST = os.environ.get("BTSOU_WEB_HOST", "0.0.0.0")
PORT = int(os.environ.get("BTSOU_WEB_PORT", "1114"))
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36")

DEFAULT_SETTINGS = {
    # 本机 VPN / 代理出口（v2ray：HTTP 10809、SOCKS5 10808）
    "vpn_proxy": "http://127.0.0.1:10809",
    # 未显式指定 proxy 的源使用哪种策略：auto = 先直连，失败走 VPN
    "default_proxy": "auto",
    "timeout": 20.0,
    "workers": 10,
    # 列表页没有磁链时，最多为多少条结果抓详情页补磁链（0 = 关闭）
    "detail_fetch_limit": 24,
    "detail_workers": 6,
    "detail_cache_ttl": 21600,
}

try:  # 可选：二维码
    import qrcode  # noqa
    import qrcode.image.svg  # noqa
    HAVE_QR = True
except Exception:  # pragma: no cover
    HAVE_QR = False


# ──────────────────────────────────────────────────────────── 配置

def load_config() -> dict:
    with open(SOURCES_FILE, encoding="utf-8") as f:
        cfg = json.load(f)
    st = dict(DEFAULT_SETTINGS)
    st.update(cfg.get("settings") or {})
    if os.environ.get("BTSOU_WEB_PROXY", "").strip():  # 环境变量优先级最高（兼容旧单元）
        st["vpn_proxy"] = os.environ["BTSOU_WEB_PROXY"].strip()
    return cfg, st


def load_sources() -> list[dict]:
    return load_config()[0].get("sources", [])


# ──────────────────────────────────────────────────────────── 工具函数

SIZE_UNITS = {"B": 1, "K": 1024, "KB": 1024, "M": 1024**2, "MB": 1024**2,
              "G": 1024**3, "GB": 1024**3, "T": 1024**4, "TB": 1024**4,
              "P": 1024**5, "PB": 1024**5}

_REL_CN = [("秒前", 1 / 86400), ("分钟前", 1 / 1440), ("小时前", 1 / 24),
           ("天前", 1), ("周前", 7), ("个月前", 30), ("年前", 365)]


def parse_size(text: str) -> int | None:
    """'1.9 GB' / '700MB' / '1,024 MB' -> bytes"""
    if not text:
        return None
    m = re.search(r"([\d.,]+)\s*(PB|TB|GB|MB|KB|B|T|G|M|K)\b", text, re.I)
    if not m:
        return None
    num = m.group(1).replace(",", "")
    try:
        val = float(num)
    except ValueError:
        return None
    unit = m.group(2).upper()
    mult = SIZE_UNITS.get(unit) or SIZE_UNITS.get(unit[0])
    return int(val * mult) if mult else None


def parse_date(text: str, now: float | None = None) -> str | None:
    """相对时间与绝对时间统一为 ISO 'YYYY-MM-DD'（相对时间返回近似日期）"""
    if not text:
        return None
    text = text.strip()
    m = re.search(r"(\d{4})[-/年.](\d{1,2})[-/月.](\d{1,2})", text)
    if m:
        y, mo, d = (int(g) for g in m.groups())
        # 上限卡到『今天+2 天』：站点里常有 2099 之类的占位日期，别原样带进结果
        limit = time.strftime("%Y-%m-%d", time.localtime((now or time.time()) + 2 * 86400))
        if 1990 <= y <= 2100 and 1 <= mo <= 12 and 1 <= d <= 31:
            iso = f"{y:04d}-{mo:02d}-{d:02d}"
            return None if iso > limit else iso
    m = re.search(r"(\d+)\s*(年前|个月前|周前|天前|小时前|分钟前|秒前)", text)
    if m:
        n = int(m.group(1))
        days = n * dict(_REL_CN)[m.group(2)]
        ts = (now or time.time()) - days * 86400
        return time.strftime("%Y-%m-%d", time.localtime(ts))
    m = re.search(r"([A-Za-z]{3})\.?\s*(\d{1,2})\s*'?(\d{2})", text)  # Mar. 5 '21
    if m:
        months = {mm: i for i, mm in enumerate(
            ["jan", "feb", "mar", "apr", "may", "jun",
             "jul", "aug", "sep", "oct", "nov", "dec"], 1)}
        mo = months.get(m.group(1).lower()[:3])
        if mo:
            return f"20{m.group(3)}-{mo:02d}-{int(m.group(2)):02d}"
    return None


def parse_popularity(text: str) -> int | None:
    if not text:
        return None
    m = re.search(r"([\d,]+)", text.replace(" ", ""))
    if not m:
        return None
    try:
        return int(m.group(1).replace(",", ""))
    except ValueError:
        return None


def strip_tags(s: str) -> str:
    return re.sub(r"<[^>]+>", "", s or "")


def clean_text(s: str | None) -> str | None:
    if not s:
        return None
    txt = _html.unescape(strip_tags(s))
    txt = txt.replace("\u3000", " ").replace("\xa0", " ")
    txt = re.sub(r"\s+", " ", txt).strip(" \t\r\n-|·")
    return txt or None


_HEX40 = re.compile(r"[a-fA-F0-9]{40}")


def extract_infohash(*candidates: str) -> str | None:
    """从 magnet / 详情链接 / 裸串里取 40 位 infohash（兼容 base32 32 位）"""
    for c in candidates:
        if not c:
            continue
        m = re.search(r"btih:([a-fA-F0-9]{40})", c)
        if m:
            return m.group(1).lower()
        m = re.search(r"btih:([a-zA-Z2-7]{32})", c)
        if m:
            return m.group(1).upper()
        # /hash/<40hex>.html、/<40hex>.html、/cili/<40hex>.html 等
        m = re.search(r"(?:hash|cili|kancili|magnet|torrent|detail|info|seed|topic|t)/"
                      r"[^\"'<>\s]*?([a-fA-F0-9]{40})", c)
        if m:
            return m.group(1).lower()
        m = _HEX40.search(c)
        if m:
            return m.group(0).lower()
    return None


def normalize_magnet(url: str, infohash: str | None) -> str | None:
    if url and url.startswith("magnet:"):
        return _html.unescape(url)
    if infohash:
        return f"magnet:?xt=urn:btih:{infohash}"
    return None


# ──────────────────────────────────────────────────────────── 关键词编码（原版 EncodeType）

def encode_keyword(kw: str, mode: str | None) -> str:
    mode = (mode or "UrlEncode").strip().lower()
    if mode in ("base64urlsafe", "base64", "b64"):
        return base64.urlsafe_b64encode(kw.encode("utf-8")).decode("ascii").rstrip("=")
    if mode == "hex":
        return kw.encode("utf-8").hex()
    if mode in ("urlencode", "url", ""):
        return urllib.parse.quote(kw)
    if mode == "raw":  # 原样（不做任何编码）
        return kw
    return urllib.parse.quote(kw)


# ──────────────────────────────────────────────────────────── 抓取（逐源代理）

_OPENERS: dict[str | None, urllib.request.OpenerDirector] = {}
_OPENERS_LOCK = threading.Lock()


def _opener(proxy_url: str | None) -> urllib.request.OpenerDirector:
    with _OPENERS_LOCK:
        if proxy_url not in _OPENERS:
            handlers = [urllib.request.ProxyHandler(
                {"http": proxy_url, "https": proxy_url} if proxy_url else {})]
            _OPENERS[proxy_url] = urllib.request.build_opener(*handlers)
        return _OPENERS[proxy_url]


def _decode_body(raw: bytes, ctype: str) -> str:
    charset = "utf-8"
    m = re.search(r"charset=([\w-]+)", ctype, re.I)
    if m:
        charset = m.group(1)
    elif re.search(r"gb2312|gbk|gb18030", ctype, re.I):
        charset = "gbk"
    try:
        return raw.decode(charset, errors="replace")
    except LookupError:
        return raw.decode("utf-8", errors="replace")


def _curl_get(url: str, referer: str | None, proxy_url: str | None,
              timeout: float) -> tuple[int, str]:
    """用系统 curl 抓（HTTP/2 + OpenSSL/GnuTLS 指纹），个别站的 Cloudflare
    只放行 curl 这类客户端的 TLS 指纹，Python urllib 会固定吃 403。"""
    fd, path = tempfile.mkstemp(prefix="btsou-")
    os.close(fd)
    cmd = ["curl", "-s", "-L", "--compressed", "--max-time", str(int(max(5, timeout))),
           "-A", UA, "-H", "Accept-Language: zh-CN,zh;q=0.9,en;q=0.8",
           "-o", path, "-w", "%{http_code}"]
    if referer:
        cmd += ["-e", referer]
    if proxy_url:
        cmd += ["-x", proxy_url]
    cmd.append(url)
    try:
        r = subprocess.run(cmd, capture_output=True, timeout=timeout + 15)
        code = (r.stdout or b"").decode("ascii", "replace").strip()
        status = int(code) if code.isdigit() else 0
        with open(path, "rb") as f:
            raw = f.read()
        if not status:
            raise RuntimeError((r.stderr or b"").decode("utf-8", "replace").strip()[:200]
                               or "curl failed")
        return status, _decode_body(raw, "")
    finally:
        try:
            os.unlink(path)
        except OSError:
            pass


def _one_get(url: str, referer: str | None, proxy_url: str | None,
             timeout: float, transport: str = "urllib") -> tuple[int, str]:
    if (transport or "urllib").lower() == "curl":
        return _curl_get(url, referer, proxy_url, timeout)
    headers = {
        "User-Agent": UA,
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,application/json;q=0.8,*/*;q=0.7",
        "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
        "Accept-Encoding": "gzip",
        "Connection": "close",
    }
    if referer:
        headers["Referer"] = referer
    last_exc: Exception | None = None
    for attempt in range(3):  # 429/503 等限流：同通道退避重试
        req = urllib.request.Request(url, headers=headers)
        try:
            with _opener(proxy_url).open(req, timeout=timeout) as resp:
                raw = resp.read()
                if (resp.headers.get("Content-Encoding") or "").lower() == "gzip":
                    try:
                        raw = gzip.decompress(raw)
                    except Exception:
                        pass
                status = resp.status
                body = _decode_body(raw, resp.headers.get("Content-Type", ""))
        except urllib.error.HTTPError as e:
            status, body = e.code, ""
            last_exc = e
        except Exception as e:
            last_exc = e
            if attempt < 2:
                time.sleep(0.8 * (attempt + 1))
                continue
            raise
        if status in (429, 503) and attempt < 2:
            time.sleep(1.2 * (attempt + 1))
            continue
        return status, body
    raise (last_exc or RuntimeError("request failed"))


_PROXY_ORDER = {
    "direct": ["direct"],
    "vpn": ["vpn"],
    "auto": ["direct", "vpn"],        # 先直连，失败/被墙再走本机 VPN
    "auto-vpn": ["vpn", "direct"],    # 先走 VPN，失败再直连（原版 Acting=TRUE 的源）
}


def http_get(url: str, referer: str | None = None, proxy_mode: str = "auto",
             settings: dict | None = None,
             transport: str = "urllib") -> tuple[int, str, str]:
    """返回 (status, body, 实际使用的通道)。通道 ∈ {direct, vpn}。

    referer=None 时自动带**同源 Referer**（浏览器在同一站内点链接就是这个行为；
    实测部分站的 Cloudflare 挑战只在带 Referer 时放行）。源里写 "referer": "" 可显式关闭。
    """
    st = settings or DEFAULT_SETTINGS
    if referer is None:
        p = urllib.parse.urlsplit(url)
        if p.scheme and p.netloc:
            referer = f"{p.scheme}://{p.netloc}/"
    vpn = st.get("vpn_proxy") or None
    timeout = float(st.get("timeout") or 12)
    order = _PROXY_ORDER.get((proxy_mode or "auto").lower(), _PROXY_ORDER["auto"])
    last: tuple[int, str, str] | None = None
    first_error: Exception | None = None
    for mode in order:
        proxy_url = vpn if mode == "vpn" else None
        if mode == "vpn" and not vpn:
            continue
        try:
            status, body = _one_get(url, referer, proxy_url, timeout, transport)
        except Exception as e:  # 连接层失败 → 换下一个通道
            first_error = first_error or e
            continue
        if status < 400:
            return status, body, mode
        last = (status, body, mode)
    if last:
        return last
    raise (first_error or RuntimeError("no route"))


# ──────────────────────────────────────────────────────────── 原版通用正则组

# 与原程序内嵌的抽取规则对齐；列表按优先级排列，逐个尝试，取第一个命中。
BATTERY = {
    "magnet": [
        r'<input[^>]*id="(?:Information_copy_text|input-magnet|magnet|magnet_link|m_link)"[^>]*value="([^"]+)"',
        r'<a[^>]*href="(magnet:[^"]+)"',
        r'(magnet:\?xt=urn:btih:[a-zA-Z0-9]+)',
        r'btih:([a-fA-F0-9]{40})',
        r'(?:hash|cili|kancili|magnet|torrent|detail|info|seed|topic)/[^"\'<>\s]*?([a-fA-F0-9]{40})',
    ],
    "size": [
        r'(?:文件大小|大小|length|size)\s*[：:]\s*(?:<[^>]+>\s*)*([\d.,]+\s*(?:TB|GB|MB|KB|B))\b',
        r'<td[^>]*>\s*([\d.,]+\s*(?:GB|MB|KB|TB))\s*</td>',
        r'<td\s+class="text-center">\s*([\d.,]+\s*(?:GB|MB|KB|TB))',
        r'([\d.,]+\s*(?:TB|GB|MB|KB))\s*</',
        r'\b([\d.,]+\s*(?:TB|GB|MB|KB))\b',
    ],
    "date": [
        r'(?:收录时间|创建时间|添加时间|发布时间|更新时间|日期|时间|date)\s*[：:]\s*(?:<[^>]+>\s*)*(\d{4}-\d{2}-\d{2})',
        r'<td[^>]*class="[^"]*coll-date[^"]*"[^>]*>\s*(.*?)\s*</td>',
        r'([A-Za-z]{3}\.?\s*\d{1,2}(?:st|nd|rd|th)?\s*,?\s*\'?\d{2,4})',
        r'(\d{4}-\d{2}-\d{2})',
        r'(\d+\s*(?:秒|分钟|小时|天|周|个月|年)前)',
    ],
    "popularity": [
        r'(?:热度|人气|点击|下载|hits|views|clicks|downloads)\s*[：:]\s*(?:<[^>]+>\s*)*([\d,]+)',
        r'(\d[\d,]*)\s*(?:次下载|人下载|次点击)',
    ],
}

# 详情页链接的优先特征（原版靠 WebView2 导航到详情页再抓磁链）
_DETAIL_HINT = re.compile(
    r"(hash|cili|kancili|magnet_search|magnet|torrent|detail|info|seed|thread|topic|/t/|bt/)", re.I)
_DETAIL_JUNK = re.compile(
    r"^(?:#|javascript:|mailto:|tel:)|\.(?:css|js|png|jpe?g|gif|svg|ico|woff2?|ttf|webp)"
    r"|/(?:static|assets|css|js|img|images|favicon|login|register|user|help|about|ad|ads)/?", re.I)

_TITLE_JUNK = re.compile(
    r"^(?:首页|主页|登录|注册|搜索|下一页|下页|尾页|上一页|末页|更多|下载|下载软件|软件|论坛|导航|"
    r"name|size|time|uploader|se|le|"
    r"home|login|register|search|next|last|prev|more|download|index)$", re.I)
# 明显不是标题的内容：磁链、URL、纯 hex（详情页/列表页里常有这类锚文本）
_TITLE_NOT = re.compile(r"^(?:magnet:|https?://|//|\{|\[|\d+$)|xt=urn:btih", re.I)


def _first(block: str, patterns: list[str]) -> str | None:
    for p in patterns:
        m = re.search(p, block, re.S | re.I)
        if not m:
            continue
        val = m.group(1) if m.groups() else m.group(0)
        if val and val.strip():
            return val.strip()
    return None


def _pick_title(block: str, src: dict) -> str | None:
    """标题优先取『详情型锚文本』，其次最长锚文本，再次 title 属性，最后整块文本。
    这样可避开表头行、分类导航、data-bs-original-title 之类的伪标题。"""
    if src.get("title"):
        return clean_text(_first(block, [src["title"]]))

    best, best_score = None, -1
    for m in re.finditer(r"<a\b([^>]*)>(.*?)</a>", block, re.S | re.I):
        attrs, inner = m.group(1), m.group(2)
        text = clean_text(inner)
        if not text or not (4 <= len(text) <= 220) or _TITLE_JUNK.match(text):
            continue
        if _TITLE_NOT.search(text):
            continue
        hm = re.search(r'href="([^"]*)"', attrs, re.I)
        href = _html.unescape(hm.group(1)) if hm else ""
        score = len(text) + (400 if _DETAIL_HINT.search(href) else 0)
        if score > best_score:
            best, best_score = text, score
    if best:
        return best

    for m in re.finditer(r'(?<![-\w])title="([^"]{4,})"', block, re.S):
        t = clean_text(m.group(1))
        if t and not _TITLE_JUNK.match(t):
            return t

    txt = clean_text(block)
    if txt and len(txt) >= 4:
        return txt[:300]
    return None


def _pick_detail(block: str, base_url: str, src: dict) -> str | None:
    if src.get("detail"):
        d = _first(block, [src["detail"]])
        return urllib.parse.urljoin(base_url, _html.unescape(d)) if d else None
    hrefs = [_html.unescape(h) for h in re.findall(r'href="([^"]+)"', block, re.I)]
    cand = [h for h in hrefs if not _DETAIL_JUNK.search(h)]
    for h in cand:  # 优先详情型链接
        if _DETAIL_HINT.search(h):
            return urllib.parse.urljoin(base_url, h)
    return urllib.parse.urljoin(base_url, cand[0]) if cand else None


def extract_magnet(block: str, src: dict) -> tuple[str | None, str | None]:
    """返回 (magnet, infohash)。源级 magnet 正则优先，否则走原版通用组；
    最后才用『href 里的裸 40 位 hex』兜底（原版也有裸 infohash 规则，但只在链接里认）。"""
    patterns = [src["magnet"]] if src.get("magnet") else BATTERY["magnet"]
    raw = _first(block, patterns)
    if raw:
        ih = extract_infohash(raw, block)
        return normalize_magnet(raw, ih), ih
    for h in re.findall(r'href="([^"]{8,})"', block, re.I):
        ih = extract_infohash(_html.unescape(h))
        if ih:
            return normalize_magnet("", ih), ih
    return None, None


# ──────────────────────────────────────────────────────────── 源解析器

def _build_url(tpl: str, keyword: str, page: int, src: dict) -> str:
    kw = encode_keyword(keyword, src.get("encoding"))
    return tpl.replace("{keyword}", kw).replace("{kw}", kw).replace("{page}", str(page))


def _candidate_urls(src: dict, keyword: str, page: int) -> list[str]:
    """主域名 + 旧镜像回退链（同步时会保留上一次的域名：镜像轮换后新域名可能反而被墙）。"""
    urls: list[str] = []
    for tpl in [src.get("list_url")] + list(src.get("mirrors") or []):
        if not tpl:
            continue
        u = _build_url(tpl, keyword, page, src)
        if u not in urls:
            urls.append(u)
    return urls[:3]


def _split_blocks(body: str, src: dict) -> list[str]:
    """列表页切块：优先原版『分割符』（literal split），其次正则 row / 页头页尾。"""
    marker = src.get("split")
    if marker:
        blocks = body.split(marker)
        return blocks[1:] if len(blocks) > 1 else blocks
    row_re = src.get("row")
    if row_re:
        return [b if isinstance(b, str) else (b[0] if b else "")
                for b in re.findall(row_re, body, re.S | re.I)]
    start, end = src.get("page_start"), src.get("page_end")
    if start and end:
        seg = re.search(re.escape(start) + "(.*?)" + re.escape(end), body, re.S)
        return [seg.group(1)] if seg else []
    return [body]


def _extract_html_rows(body: str, url: str, src: dict, via: str) -> list[dict]:
    rows: list[dict] = []
    seen_titles: set[str] = set()
    for b in _split_blocks(body, src):
        if not b or len(b.strip()) < 20:
            continue
        title = _pick_title(b, src)
        magnet, ih = extract_magnet(b, src)
        size_raw = _first(b, [src["size"]] if src.get("size") else BATTERY["size"])
        date_raw = _first(b, [src["date"]] if src.get("date") else BATTERY["date"])
        pop_raw = _first(b, [src["popularity"]] if src.get("popularity") else BATTERY["popularity"])
        detail = _pick_detail(b, url, src) if (src.get("detail") or True) else None
        # 有效行判定：有磁链/哈希必留；否则要有『体积 + (日期或详情页)』这类成对证据。
        # 这样能滤掉表头行、分类导航、整页文本兜底等伪结果。
        has_mag = bool(ih or magnet)
        if not title:
            continue
        if not has_mag and not (size_raw and (date_raw or detail)):
            continue
        if not has_mag and len(title) > 220:  # 整页文本兜底 → 不是单条结果
            continue
        key = ih or title.lower()
        if key in seen_titles:
            continue
        seen_titles.add(key)
        rows.append({
            "title": title,
            "size_bytes": parse_size(size_raw or ""),
            "size_raw": (size_raw or "").strip() or None,
            "date": parse_date(date_raw or ""),
            "popularity": parse_popularity(pop_raw or ""),
            "infohash": ih,
            "magnet": magnet,
            "detail_url": detail,
            "source": src["id"],
            "source_name": src.get("name", src["id"]),
            "via": via,
        })
    return rows


def parse_html_source(src: dict, keyword: str, page: int, settings: dict) -> list[dict]:
    """主域名 + 回退镜像依次尝试；某个镜像被墙或改版时不至于整个源失效。"""
    mode = src.get("proxy") or settings["default_proxy"]
    transport = src.get("transport", "urllib")
    last_error: Exception | None = None
    got_200 = False
    for url in _candidate_urls(src, keyword, page):
        try:
            status, body, via = http_get(url, referer=src.get("referer"),
                                         proxy_mode=mode, settings=settings,
                                         transport=transport)
        except Exception as e:
            last_error = e
            continue
        if status != 200:
            last_error = RuntimeError(f"HTTP {status}（{via}）")
            continue
        got_200 = True
        rows = _extract_html_rows(body, url, src, via)
        if rows:
            return rows
    if got_200:  # 页面拿到了，只是确实没结果
        return []
    raise (last_error or RuntimeError("no candidate url"))


def _extract_json_rows(body: str, url: str, src: dict, via: str) -> list[dict]:
    data = json.loads(body)

    node = data
    for part in (src.get("json_list_path") or "").split("."):
        if not part:
            continue
        if part.isdigit() and isinstance(node, list):
            node = node[int(part)]
        elif isinstance(node, dict):
            node = node.get(part)
        else:
            node = None
    if not isinstance(node, list):
        return []

    fields = src.get("json_fields", {})
    rows = []
    for ent in node:
        if not isinstance(ent, dict):
            continue

        def f(k):
            path = fields.get(k)
            if not path:
                return None
            cur = ent
            for part in path.split("."):
                cur = cur.get(part) if isinstance(cur, dict) else None
            return cur if isinstance(cur, (str, int, float)) else None

        title = f("title")
        mag = f("magnet")
        ih = extract_infohash(str(mag or ""), str(f("infohash") or ""))
        detail = None
        if f("id") is not None and src.get("detail_url_template"):
            detail = src["detail_url_template"].replace("{id}", str(f("id")))
        rows.append({
            "title": clean_text(str(title)) if title is not None else None,
            "size_bytes": int(f("size")) if str(f("size") or "").isdigit() else parse_size(str(f("size") or "")),
            "size_raw": (str(f("size")) if f("size") is not None else None),
            "date": parse_date(str(f("date") or "")),
            "popularity": parse_popularity(str(f("popularity") or "")),
            "infohash": ih,
            "magnet": normalize_magnet(str(mag or ""), ih),
            "detail_url": detail,
            "source": src["id"],
            "source_name": src.get("name", src["id"]),
            "via": via,
        })
    return [r for r in rows if r["title"] or r["infohash"]]


def parse_json_source(src: dict, keyword: str, page: int, settings: dict) -> list[dict]:
    mode = src.get("proxy") or settings["default_proxy"]
    transport = src.get("transport", "urllib")
    last_error: Exception | None = None
    got_200 = False
    for url in _candidate_urls(src, keyword, page):
        try:
            status, body, via = http_get(url, referer=src.get("referer"),
                                         proxy_mode=mode, settings=settings,
                                         transport=transport)
        except Exception as e:
            last_error = e
            continue
        if status != 200:
            last_error = RuntimeError(f"HTTP {status}（{via}）")
            continue
        got_200 = True
        try:
            rows = _extract_json_rows(body, url, src, via)
        except Exception as e:
            last_error = e
            continue
        if rows:
            return rows
    if got_200:
        return []
    raise (last_error or RuntimeError("no candidate url"))


def parse_demo_source(src: dict, keyword: str, page: int, settings: dict) -> list[dict]:
    """演示源：不联网，用来验证整条链路（解析/归一化/去重/筛选/排序/导出）"""
    import hashlib
    if page > 1:
        return []
    rows = []
    for i in range(src.get("demo_rows", 24)):
        seed = hashlib.sha1(f"{keyword}|{i}".encode()).hexdigest()
        size_mb = 300 + (int(seed[:4], 16) % 9000)
        rows.append({
            "title": f"{keyword} DEMO.{2020 + i % 5} 1080p WEB-DL x264 AAC-{seed[:6].upper()}"
                     + (".mp4" if i % 3 else ".mkv"),
            "size_bytes": size_mb * 1024**2,
            "size_raw": f"{size_mb / 1024:.2f} GB",
            "date": time.strftime("%Y-%m-%d", time.localtime(time.time() - i * 86400 * 3)),
            "popularity": int(seed[4:8], 16) % 3000,
            "infohash": seed,
            "magnet": f"magnet:?xt=urn:btih:{seed}&dn={urllib.parse.quote(keyword)}",
            "detail_url": None,
            "source": src["id"],
            "source_name": src.get("name", src["id"]),
            "via": "offline",
        })
    return rows


PARSERS = {"html": parse_html_source, "json": parse_json_source, "demo": parse_demo_source}


# ──────────────────────────────────────────────────────────── 与作者同步（/api/sync）

_GEN_LOCK = threading.Lock()
_GEN_MOD = None
_LAST_SYNC = 0.0
SYNC_MIN_INTERVAL = 15.0  # 秒：避免连点把作者服务器打爆


def load_generator():
    """加载 tools/gen_sources.py（不复制逻辑：生成/比对口径与命令行完全一致）。"""
    global _GEN_MOD
    with _GEN_LOCK:
        if _GEN_MOD is None:
            import importlib.util
            path = os.path.join(APP_DIR, "tools", "gen_sources.py")
            spec = importlib.util.spec_from_file_location("btsou_gen_sources", path)
            mod = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(mod)
            _GEN_MOD = mod
        return _GEN_MOD


def sync_sources(dry_run: bool) -> dict:
    global _LAST_SYNC
    mod = load_generator()
    if dry_run:
        return mod.sync(dry_run=True, out=SOURCES_FILE)
    with _GEN_LOCK:
        wait = SYNC_MIN_INTERVAL - (time.time() - _LAST_SYNC)
        if wait > 0:
            raise RuntimeError(f"同步过于频繁，请 {wait:.0f} 秒后再试")
        res = mod.sync(dry_run=False, out=SOURCES_FILE)
        _LAST_SYNC = time.time()
        return res


# ──────────────────────────────────────────────────────────── 详情页补磁链

_DETAIL_CACHE: dict[str, tuple[float, str | None, str | None]] = {}
_DETAIL_LOCK = threading.Lock()


def detail_magnet(url: str, src: dict, settings: dict,
                  referer: str | None = None) -> tuple[str | None, str | None]:
    ttl = float(settings.get("detail_cache_ttl") or 21600)
    now = time.time()
    with _DETAIL_LOCK:
        hit = _DETAIL_CACHE.get(url)
        if hit and now - hit[0] < ttl:
            return hit[1], hit[2]
    try:
        status, body, via = http_get(url, referer=(referer if referer is not None
                                                    else src.get("referer")),
                                     proxy_mode=src.get("proxy") or settings["default_proxy"],
                                     settings=settings,
                                     transport=src.get("transport", "urllib"))
        if status != 200:
            return None, None
        mag, ih = extract_magnet(body, src)
    except Exception:
        return None, None
    with _DETAIL_LOCK:
        _DETAIL_CACHE[url] = (now, mag, ih)
    return mag, ih


def fill_magnets(rows: list[dict], src: dict, settings: dict,
                 referer: str | None = None) -> int:
    limit = int(settings.get("detail_fetch_limit") or 0)
    if limit <= 0:
        return 0
    todo = [r for r in rows if not r.get("infohash") and r.get("detail_url")][:limit]
    if not todo:
        return 0
    done = 0
    workers = max(1, int(settings.get("detail_workers") or 4))
    with ThreadPoolExecutor(max_workers=workers) as ex:
        futs = {ex.submit(detail_magnet, r["detail_url"], src, settings, referer): r
                for r in todo}
        for fut in as_completed(futs):
            r = futs[fut]
            try:
                mag, ih = fut.result()
            except Exception:
                continue
            if ih or mag:
                r["infohash"] = ih
                r["magnet"] = mag or normalize_magnet("", ih)
                r["magnet_from"] = "detail"
                done += 1
    return done


# ──────────────────────────────────────────────────────────── 聚合

def run_search(keyword: str, source_ids: list[str] | None, pages: int = 1) -> dict:
    _, settings = load_config()
    all_sources = load_sources()
    sources = [s for s in all_sources if s.get("enabled")]
    if source_ids:
        want = set(source_ids)
        sources = [s for s in sources if s["id"] in want]

    results: list[dict] = []
    errors: list[dict] = []
    status: list[dict] = []
    lock = threading.Lock()
    t0 = time.time()

    jobs = []
    for src in sources:
        for page in range(1, max(1, pages) + 1):
            jobs.append((src, page))

    workers = max(1, int(settings.get("workers") or 8))
    with ThreadPoolExecutor(max_workers=workers) as ex:
        futs = {}
        for src, page in jobs:
            parser = PARSERS.get(src.get("type", "html"))
            if not parser:
                with lock:
                    errors.append({"source": src["id"], "error": "unknown type"})
                continue
            futs[ex.submit(parser, src, keyword, page, settings)] = (src, page)
        for fut in as_completed(futs):
            src, page = futs[fut]
            try:
                rows = fut.result()
            except Exception as e:  # 单源失败不影响整体
                with lock:
                    errors.append({"source": src["id"], "source_name": src.get("name"),
                                   "page": page, "error": f"{type(e).__name__}: {e}"})
                continue
            # 列表页没磁链 → 抓详情页补齐（原版同样会进详情页）
            filled = 0
            if src.get("type", "html") == "html" and src.get("detail_fetch", True):
                try:
                    list_url = _build_url(src.get("list_url", ""), keyword, page, src)
                    filled = fill_magnets(rows, src, settings, referer=list_url)
                except Exception:
                    pass
            with lock:
                results.extend(rows)
                status.append({"source": src["id"], "source_name": src.get("name"),
                               "page": page, "rows": len(rows), "magnet_filled": filled,
                               "via": rows[0]["via"] if rows else None})

    # 去重：优先 infohash，其次标题
    seen, deduped = set(), []
    for r in results:
        key = r.get("infohash") or (r.get("title") or "").strip().lower()
        if not key or key in seen:
            continue
        seen.add(key)
        deduped.append(r)

    return {
        "keyword": keyword,
        "total_fetched": len(results),
        "total": len(deduped),
        "elapsed_ms": int((time.time() - t0) * 1000),
        "sources_used": len(sources),
        "with_magnet": sum(1 for r in deduped if r.get("magnet")),
        "errors": errors,
        "source_status": status,
        "results": deduped,
    }


def probe_source(src: dict, keyword: str) -> dict:
    """调试单个源：返回 HTTP 状态、走哪个通道、抓到的原始片段、解析结果与失败原因。"""
    _, settings = load_config()
    t0 = time.time()
    out: dict = {"ok": False, "source": src.get("id"), "type": src.get("type"),
                 "proxy_mode": src.get("proxy") or settings["default_proxy"],
                 "encoding": src.get("encoding") or "UrlEncode"}
    try:
        if src.get("type", "html") == "demo":
            rows = PARSERS["demo"](src, keyword, 1, settings)
            out.update(ok=True, rows=len(rows), sample=rows[:3])
            return out

        urls = _candidate_urls(src, keyword, 1)
        url = urls[0]
        out["url"] = url
        out["url_candidates"] = urls
        status, body, via = http_get(url, referer=src.get("referer"),
                                     proxy_mode=src.get("proxy") or settings["default_proxy"],
                                     settings=settings,
                                     transport=src.get("transport", "urllib"))
        out.update(http_status=status, via=via, bytes=len(body), body_head=body[:800])
        if status != 200:
            out["error"] = f"HTTP {status}"
            out["hint"] = "换通道仍被拦（Cloudflare/反爬）。可把该源 proxy 改成另一种，或关掉。"
            return out

        rows = PARSERS[src.get("type", "html")](src, keyword, 1, settings)
        filled = 0
        if src.get("type", "html") == "html" and src.get("detail_fetch", True):
            try:
                filled = fill_magnets(rows, src, settings, referer=url)
            except Exception:
                pass
        out["ok"] = True
        out["rows"] = len(rows)
        out["sample"] = rows[:3]
        out["magnet_filled"] = filled
        out["with_magnet"] = sum(1 for r in rows if r.get("magnet"))
        if not rows:
            out["hint"] = ("页面拿到了但切块/字段没匹配上 → 检查 split（分割符）与字段正则；"
                           "body_head 是真实 HTML 开头。")
        return out
    except Exception as e:
        out["error"] = f"{type(e).__name__}: {e}"
        out["hint"] = ("连接/解析失败。常见原因：站点需要 Referer、被 Cloudflare 拦、"
                       "本机网络不通，或该源应走 VPN（proxy=vpn）。")
        return out
    finally:
        out["elapsed_ms"] = int((time.time() - t0) * 1000)


# ──────────────────────────────────────────────────────────── HTTP

class Handler(BaseHTTPRequestHandler):
    server_version = "BTSOU-Web/1.1"

    def log_message(self, fmt, *args):  # 安静日志
        sys.stderr.write("[%s] %s\n" % (time.strftime("%H:%M:%S"), fmt % args))

    def _send(self, code: int, body: bytes, ctype: str):
        self.send_response(code)
        self.send_header("Content-Type", ctype)
        self.send_header("Content-Length", str(len(body)))
        self.send_header("Cache-Control", "no-store")
        self.send_header("X-Content-Type-Options", "nosniff")
        self.end_headers()
        try:
            self.wfile.write(body)
        except BrokenPipeError:
            pass

    def _json(self, obj, code=200):
        self._send(code, json.dumps(obj, ensure_ascii=False).encode("utf-8"),
                   "application/json; charset=utf-8")

    def _static(self, rel: str):
        path = os.path.normpath(os.path.join(WEB_DIR, rel.lstrip("/")))
        if not path.startswith(WEB_DIR) or not os.path.isfile(path):
            self._send(404, b"not found", "text/plain; charset=utf-8")
            return
        ctype = {"html": "text/html; charset=utf-8", "js": "application/javascript; charset=utf-8",
                 "css": "text/css; charset=utf-8", "svg": "image/svg+xml"}.get(
                     path.rsplit(".", 1)[-1], "application/octet-stream")
        with open(path, "rb") as f:
            self._send(200, f.read(), ctype)

    def do_POST(self):
        u = urllib.parse.urlparse(self.path)
        if u.path not in ("/api/probe", "/api/sync"):
            return self._send(404, b"not found", "text/plain; charset=utf-8")
        try:
            n = int(self.headers.get("Content-Length") or 0)
            raw = self.rfile.read(n).decode("utf-8") if n else "{}"
            payload = json.loads(raw or "{}")
        except Exception as e:
            return self._json({"ok": False, "error": f"请求体不是合法 JSON: {e}"}, 400)

        if u.path == "/api/sync":
            # 手动与作者同步源清单：拉 ResPool.txt/ApiMapping.txt → 重建 sources.json
            # dryerun=true 只比对不写盘。改完即时生效（每次请求都重新读 sources.json）。
            try:
                res = sync_sources(bool(payload.get("dry_run")))
                _, st = load_config()
                res["vpn_proxy"] = st.get("vpn_proxy")
                res["take_effect"] = "已生效（无需重启）" if not res.get("dry_run") else "仅预览"
                return self._json(res)
            except Exception as e:
                return self._json({"ok": False, "error": f"{type(e).__name__}: {e}"}, 500)

        src = payload.get("source") or {}
        if not isinstance(src, dict) or (not src.get("list_url") and src.get("type") != "demo"):
            return self._json({"ok": False, "error": "缺少 source.list_url"}, 400)
        src.setdefault("id", "__probe__")
        src.setdefault("type", "html")
        kw = (payload.get("kw") or "test").strip()
        return self._json(probe_source(src, kw))

    def do_GET(self):
        u = urllib.parse.urlparse(self.path)
        q = urllib.parse.parse_qs(u.query)
        if u.path in ("/", "/index.html"):
            return self._static("index.html")
        if u.path == "/healthz":
            cfg, st = load_config()
            srcs = load_sources()
            return self._json({"ok": True, "sources": len(srcs),
                               "respool_version": (cfg.get("globals_from_respool") or {}).get("版本", "").strip(),
                               "enabled": sum(1 for s in srcs if s.get("enabled")),
                               "vpn_proxy": st.get("vpn_proxy"),
                               "default_proxy": st.get("default_proxy"),
                               "qr": HAVE_QR, "t": time.time()})
        if u.path == "/api/sources":
            srcs = [{k: v for k, v in s.items()
                     if k in ("id", "name", "type", "enabled", "note", "list_url",
                              "proxy", "encoding", "group")}
                    for s in load_sources()]
            return self._json({"sources": srcs, "qr": HAVE_QR})
        if u.path == "/api/search":
            kw = (q.get("kw") or [""])[0].strip()
            if not kw:
                return self._json({"error": "缺少关键词"}, 400)
            ids = [x for x in (q.get("sources") or [""])[0].split(",") if x]
            pages = int((q.get("pages") or ["1"])[0] or 1)
            try:
                return self._json(run_search(kw, ids or None, pages))
            except Exception as e:
                return self._json({"error": f"{type(e).__name__}: {e}"}, 500)
        if u.path == "/api/qr":
            text = (q.get("text") or [""])[0]
            if not text:
                return self._json({"error": "缺少 text"}, 400)
            if not HAVE_QR:
                return self._json({"error": "未安装 qrcode 模块"}, 501)
            import qrcode as _q
            import qrcode.image.svg as _qs
            img = _q.make(text, image_factory=_qs.SvgPathImage, box_size=5, border=2)
            import io as _io
            buf = _io.BytesIO()
            img.save(buf)
            return self._send(200, buf.getvalue(), "image/svg+xml")
        if u.path.startswith("/static/"):
            return self._static(u.path[len("/static/"):])
        self._send(404, b"not found", "text/plain; charset=utf-8")


def main():
    if not os.path.isfile(SOURCES_FILE):
        print(f"[!] 缺少 {SOURCES_FILE}", file=sys.stderr)
        sys.exit(1)
    cfg, st = load_config()
    srcs = cfg.get("sources", [])
    srv = ThreadingHTTPServer((HOST, PORT), Handler)
    srv.daemon_threads = True
    print(f"BTSOU-Web listening on http://{HOST}:{PORT}  "
          f"(sources={len(srcs)}/{sum(1 for s in srcs if s.get('enabled'))} enabled, "
          f"default_proxy={st.get('default_proxy')}, vpn={st.get('vpn_proxy')}, qr={HAVE_QR})")
    try:
        srv.serve_forever()
    except KeyboardInterrupt:
        pass


if __name__ == "__main__":
    main()
