"""并行抓 N 个 JoySpace 链接的正文。底层走内置API模块。"""
from __future__ import annotations

from _monitor_autoload import finbox_autoload
finbox_autoload()

import argparse
import concurrent.futures as cf
import json
import re
import sys
from pathlib import Path
from typing import Iterable

# 本地 api/auth/utils 已内置，直接 import
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

from api.gateway import JoySpaceClient  # noqa: E402
from api import document, aitable, sheets  # noqa: E402
from utils.url_parser import parse_page_url  # noqa: E402

MAX_PARALLEL = 8
SHEET_ROW_CAP = 500

PAGE_ID_RE = re.compile(r"/(?:pages|sheets|aitable)/([A-Za-z0-9]+)")

_client = None
_client_token = None
_client_team_id = None

def _get_client(token: str = None, team_id: str = None) -> JoySpaceClient:
    global _client, _client_token, _client_team_id
    effective_token = token or _client_token
    effective_team_id = team_id or _client_team_id
    if _client is None or (effective_token and effective_token != _client_token) or (effective_team_id and effective_team_id != _client_team_id):
        _client = JoySpaceClient(sso_token=effective_token, team_id=effective_team_id)
        _client_token = effective_token
        _client_team_id = effective_team_id
    return _client


def extract_page_id(url: str) -> str | None:
    try:
        return parse_page_url(url)
    except ValueError:
        return None


def classify_link(url: str) -> str:
    if "/pages/" in url:
        return "page"
    if "/sheets/" in url:
        return "sheet"
    if "/aitable/" in url:
        return "aitable"
    return "unknown"


def dedup_links(links: Iterable[str]) -> list[str]:
    seen: set[str] = set()
    out: list[str] = []
    for x in links:
        if x not in seen:
            seen.add(x)
            out.append(x)
    return out


def batch_links(links: list[str]) -> list[list[str]]:
    return [links[i:i + MAX_PARALLEL] for i in range(0, len(links), MAX_PARALLEL)]

def fetch_one(idx: int, url: str) -> dict:
    """idx 用来生成编号 A/B/C..."""
    code = chr(ord("A") + idx) if idx < 26 else f"D{idx}"
    page_id = extract_page_id(url)
    kind = classify_link(url)
    base = {"id": code, "url": url, "type": kind, "title": "", "modified": "-", "body": "", "warning": None}
    client = _get_client()

    if not page_id or kind == "unknown":
        base["warning"] = "无法解析 page_id 或类型未知"
        return base

    try:
        meta = document.get_page_basic_info(client, {"page_id": page_id})
    except Exception as e:
        base["warning"] = str(e)[:200]
        return base
    base["title"] = meta.get("data", {}).get("title", "") or meta.get("title", "")
    base["modified"] = meta.get("data", {}).get("modifyTime", "") or meta.get("modifyTime", "-") or "-"

    try:
        if kind == "page":
            res = document.get_normal_json_content(client, {"page_id": page_id})
            body = res.get("data", {}).get("content") or res.get("content") or ""
            if isinstance(body, list):
                body = "\n".join(json.dumps(b, ensure_ascii=False) if not isinstance(b, str) else b for b in body)
            base["body"] = body
        elif kind == "sheet":
            res = sheets.get_et_range_data(client, {
                "page_id": page_id, "worksheet_id": "1",
                "row_from": 0, "row_to": SHEET_ROW_CAP,
                "col_from": 0, "col_to": 30,
            })
            base["body"] = json.dumps(res.get("data", res), ensure_ascii=False)[:200_000]
            base["warning"] = f"sheet 截断为前 {SHEET_ROW_CAP} 行"
        elif kind == "aitable":
            res = aitable.list_records_by_page(client, {
                "page_id": page_id, "sheet_id": "1",
                "page_size": 200, "page_num": 1,
            })
            base["body"] = json.dumps(res.get("data", res), ensure_ascii=False)[:200_000]
    except Exception as e:
        base["warning"] = str(e)[:200]

    return base


def fetch_all(links: list[str]) -> list[dict]:
    links = dedup_links(links)
    results: list[dict] = [None] * len(links)  # type: ignore
    with cf.ThreadPoolExecutor(max_workers=MAX_PARALLEL) as ex:
        futs = {ex.submit(fetch_one, i, url): i for i, url in enumerate(links)}
        for fut in cf.as_completed(futs):
            i = futs[fut]
            try:
                results[i] = fut.result()
            except Exception as e:
                results[i] = {"id": chr(ord("A") + i), "url": links[i], "type": "unknown",
                              "title": "", "modified": "-", "body": "", "warning": f"exception: {e}"}
    return results


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--params", default="{}", help="JSON 格式参数（统一入口路由）")
    parser.add_argument("--token", help="SSO Token")
    parser.add_argument("--team-id", help="Team ID")
    parser.add_argument("--links-json", help='JSON array of URLs')
    parser.add_argument("--links-file", help="File with one URL per line")
    parser.add_argument("--out", default=None)
    args = parser.parse_args()

    # 支持 --params JSON 路由模式
    if args.params and args.params != "{}":
        try:
            p = json.loads(args.params)
        except json.JSONDecodeError:
            p = {}
        if not args.links_json and not args.links_file:
            links_data = p.get("links") or p.get("urls") or []
            if links_data:
                args.links_json = json.dumps(links_data, ensure_ascii=False)
        if not args.out:
            args.out = p.get("out")

    if args.links_json:
        try:
            links = json.loads(args.links_json)
        except json.JSONDecodeError as e:
            print(json.dumps({"status": "error", "error": f"links-json 格式错误: {e}"}, ensure_ascii=False), file=sys.stderr)
            return 1
    elif args.links_file:
        links = [ln.strip() for ln in Path(args.links_file).read_text(encoding="utf-8-sig").splitlines() if ln.strip()]
    else:
        print(json.dumps({"status": "error", "error": "需要提供 links 或 urls 参数"}, ensure_ascii=False), file=sys.stderr)
        return 1

    links = dedup_links(links)
    if len(links) == 0:
        print(json.dumps({"status": "error", "error": "未提供任何文档链接"}, ensure_ascii=False), file=sys.stderr)
        return 1
    if len(links) < 2:
        print(json.dumps({"status": "error", "error": "至少需要 2 篇不同文档才能进行对照分析"}, ensure_ascii=False), file=sys.stderr)
        return 1

    # 初始化全局 client，传入 token/team_id
    _get_client(token=args.token, team_id=args.team_id)

    if not args.out:
        import tempfile
        args.out = str(Path(tempfile.gettempdir()) / "synth_fetch_result.json")

    docs = fetch_all(links)
    Path(args.out).write_text(json.dumps({"docs": docs}, ensure_ascii=False, indent=2), encoding="utf-8")
    print(json.dumps({"status": "success", "summary": f"已抓取 {len(docs)} 篇文档, {len([d for d in docs if d.get('warning')])} 个警告", "count": len(docs), "output_file": args.out, "warnings": [d["warning"] for d in docs if d.get("warning")]}, ensure_ascii=False))
    return 0


if __name__ == "__main__":
    sys.exit(main())
