#!/usr/bin/env python3
"""End-to-end JoySpace desensitize pipeline.

Uses built-in API modules for API access.

Steps
-----
1. Read the source JoySpace page JSON via built-in API.
2. Run :mod:`desensitize_content` on the JSON in memory.
3. Optionally export the desensitized content as Markdown for human review.
4. Create a new JoySpace page under the *parent folder* of the source page
   (or an explicit ``--location-url``) with title ``<原标题>_脱敏版``.
"""

from __future__ import annotations

from _monitor_autoload import finbox_autoload
finbox_autoload()

import argparse
import json
import sys
import tempfile
from pathlib import Path
from typing import Any

THIS_DIR = Path(__file__).resolve().parent

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

# 保留本地 desensitize_content 模块
sys.path.insert(0, str(THIS_DIR))

from desensitize_content import desensitize_content  # noqa: E402
from api.gateway import JoySpaceClient  # noqa: E402
from api import document  # noqa: E402
from utils.url_parser import parse_page_url  # noqa: E402


def _log(stage: str, message: str) -> None:
    """Print a phased progress line to stderr so JSON on stdout stays parseable."""
    print(f"[joyspace-desensitize] {stage}: {message}", file=sys.stderr, flush=True)


def _count_text_leaves(content: list[Any]) -> tuple[int, int]:
    """Return (total text leaves, leaves containing digits) — used for before/after preview."""
    total = 0
    numeric = 0

    def walk(node: Any) -> None:
        nonlocal total, numeric
        if isinstance(node, dict):
            t = node.get("text")
            if isinstance(t, str) and t:
                total += 1
                if any(ch.isdigit() for ch in t):
                    numeric += 1
            for child in node.get("children", []) or []:
                walk(child)
        elif isinstance(node, list):
            for item in node:
                walk(item)

    walk(content)
    return total, numeric


def _fetch_basic_info(client: JoySpaceClient, page_url: str) -> dict[str, Any]:
    page_id = parse_page_url(page_url)
    return document.get_page_basic_info(client, {"page_id": page_id})


def _fetch_content(client: JoySpaceClient, page_url: str) -> dict[str, Any]:
    page_id = parse_page_url(page_url)
    return document.get_normal_json_content(client, {"page_id": page_id})


def _markdown_from_content(content: list[Any]) -> str:
    """Render Markdown via the local exporter for human review only."""
    try:
        from export_team_folder_md import content_to_markdown  # type: ignore
        return content_to_markdown(content)
    except Exception:
        return ""


def run(
    page_url: str,
    *,
    workdir: Path,
    location_url: str | None,
    title_override: str | None,
    keep_intermediate: bool,
    dry_run: bool,
    sso_token: str | None = None,
) -> dict[str, Any]:
    workdir.mkdir(parents=True, exist_ok=True)
    client = JoySpaceClient(sso_token=sso_token)

    _log("step 1/4", f"fetching basic info for {page_url}")
    info_envelope = _fetch_basic_info(client, page_url)
    info = info_envelope.get("data") or {}
    page_id = info.get("pageId") or ""
    title = info.get("title") or "未命名"
    team_id = info.get("teamId") or ""
    parent_id = info.get("parentId") or ""

    _log("step 2/4", f"fetching page content (title='{title}', pageId={page_id})")
    raw_envelope = _fetch_content(client, page_url)
    raw_data = raw_envelope.get("data") or {}
    content = raw_data.get("content") or []
    if not isinstance(content, list) or not content:
        return {"status": "error", "error": f"页面内容为空或格式异常，无法脱敏: {page_url}"}

    raw_path = workdir / f"{page_id}_raw.json"
    raw_path.write_text(json.dumps(raw_envelope, ensure_ascii=False, indent=2), encoding="utf-8")

    raw_md = _markdown_from_content(content)
    if raw_md:
        (workdir / f"{page_id}_raw.md").write_text(raw_md, encoding="utf-8")

    total_leaves, numeric_before = _count_text_leaves(content)
    _log("step 3/4", f"desensitizing ({numeric_before} of {total_leaves} text leaves contain digits)")
    desensitize_content(content)
    _, numeric_after = _count_text_leaves(content)
    _log("step 3/4", f"done — {numeric_before - numeric_after} numeric leaves blanked, {numeric_after} kept as deltas")

    desens_envelope = {"data": {"pageType": raw_data.get("pageType", 13), "content": content}}
    desens_path = workdir / f"{page_id}_desens.json"
    desens_path.write_text(json.dumps(desens_envelope, ensure_ascii=False, indent=2), encoding="utf-8")

    desens_md = _markdown_from_content(content)
    if desens_md:
        (workdir / f"{page_id}_desens.md").write_text(desens_md, encoding="utf-8")

    new_title = title_override or f"{title}_脱敏版"

    if dry_run:
        return {
            "status": "dry-run",
            "source": {"pageId": page_id, "title": title, "teamId": team_id, "parentId": parent_id},
            "desensitizedJson": str(desens_path),
        }

    # 创建脱敏文档
    create_params = {"title": new_title, "content": content}
    if location_url:
        from utils.url_parser import parse_location_url
        tid, fid = parse_location_url(location_url)
        create_params["team_id"] = tid or "root"
        create_params["folder_id"] = fid or "root"
    elif team_id and parent_id:
        create_params["team_id"] = team_id
        create_params["folder_id"] = parent_id
    else:
        create_params["team_id"] = "root"
        create_params["folder_id"] = "root"

    _log("step 4/4", f"publishing as '{new_title}' under teamId={team_id or '<personal>'} parentId={parent_id or '<root>'}")
    create_result = document.create_doc_routing(client, create_params)
    new_data = create_result.get("data") or {}

    summary = {
        "status": create_result.get("status", "success"),
        "summary": f"脱敏完成: {numeric_before - numeric_after} 个数值已替换, 新文档 '{new_data.get('title', '')}'",
        "source": {
            "pageId": page_id,
            "title": title,
            "teamId": team_id,
            "parentId": parent_id,
            "link": info.get("link") or page_url,
        },
        "desensitized": {
            "pageId": new_data.get("pageId"),
            "title": new_data.get("title"),
            "link": new_data.get("link"),
            "teamId": new_data.get("teamId"),
            "parentId": new_data.get("parentId"),
        },
        "stats": {
            "textLeaves": total_leaves,
            "numericBefore": numeric_before,
            "numericAfter": numeric_after,
            "blanked": numeric_before - numeric_after,
        },
        "artifacts": {
            "rawJson": str(raw_path),
            "desensitizedJson": str(desens_path),
        },
    }
    _log("done", f"new page → {new_data.get('link') or '(no link returned)'}")

    if not keep_intermediate:
        for p in (raw_path, desens_path):
            try:
                p.unlink()
            except OSError:
                pass

    return summary


def main() -> int:
    parser = argparse.ArgumentParser(description="JoySpace page desensitize pipeline")
    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("--page-url", help="Source JoySpace page URL")
    parser.add_argument("--location-url", help="Override target location (team folder URL); default is the source page's parent folder")
    parser.add_argument("--title", help="Override new doc title (default: <原标题>_脱敏版)")
    parser.add_argument(
        "--workdir",
        default=str(Path(tempfile.gettempdir()) / "joyspace-desensitize"),
        help="Directory for intermediate JSON / Markdown artifacts",
    )
    parser.add_argument("--keep-intermediate", action="store_true", help="Do not delete intermediate JSON files after success")
    parser.add_argument("--dry-run", action="store_true", help="Print the create payload without writing to JoySpace")
    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.page_url:
            args.page_url = p.get("page_url") or p.get("url_or_id", "")
        if not args.location_url:
            args.location_url = p.get("location_url")
        if not args.title:
            args.title = p.get("title")

    if not args.page_url:
        print(json.dumps({"status": "error", "error": "缺少 page_url 参数，请提供 JoySpace 页面 URL"}, ensure_ascii=False), file=sys.stderr)
        return 1

    summary = run(
        args.page_url,
        workdir=Path(args.workdir),
        location_url=args.location_url,
        title_override=args.title,
        keep_intermediate=args.keep_intermediate,
        dry_run=args.dry_run,
        sso_token=args.token,
    )
    print(json.dumps(summary, ensure_ascii=False, indent=2))
    return 0


if __name__ == "__main__":
    try:
        sys.exit(main())
    except SystemExit:
        raise
    except Exception as exc:  # pragma: no cover
        print(json.dumps({"status": "error", "error": str(exc)}, ensure_ascii=False), file=sys.stderr)
        sys.exit(1)
