"""
JoySpace 权限管理 —— 批量开通文件夹权限（借鉴 joyspace-permission-grant skill）。

能力：
- grant_folder_permissions: 批量给文件夹下所有文档开通权限(双模式确认架构)
  - --prepare(默认): 递归扫描文件夹+生成权限计划, 不执行开通
  - --confirm: 从计划执行静默权限开通(POST /v1/shares, permission_type=2 Reader)
- scan_folder_recursive: 递归扫描文件夹下所有文档(API+Playwright双源)

借鉴 joyspace-permission-grant 的双模式强制确认架构(--prepare生成清单后sys.exit, --confirm才执行),
permission_type=2 硬编码只读防越权。
"""

import json
import os
import sys
import time

import requests

JOYSPACE_API = "https://apijoyspace.jd.com"
PERMISSION_TYPE = 2  # Reader 只读, 硬编码防越权
SHARE_SILENT = True
SHARE_SKIP_NOTIFICATION = True


def _scan_folder_api(client, team_id: str, folder_id: str, depth=0, max_depth=30, visited=None):
    """通过 API 递归扫描文件夹下所有文档和子文件夹(无需Playwright)。

    返回: [{pageId, title, pageType, folderId}]
    """
    if visited is None:
        visited = set()
    if folder_id in visited or depth > max_depth:
        return []
    visited.add(folder_id)
    results = []
    try:
        data = client.joyspace_get(f"/v1/spaces/{team_id}/pages",
                                    params={"categoryId": folder_id, "length": 200, "start": 0, "sort": "-updated_at"})
        pages = data.get("data", {}).get("pages", []) if isinstance(data.get("data"), dict) else (data.get("data") or [])
        for p in pages:
            page_type = p.get("pageType")
            results.append({
                "pageId": p.get("id") or p.get("pageId"),
                "title": p.get("title") or "(未命名)",
                "pageType": page_type,
                "folderId": folder_id,
            })
            # 子文件夹递归(pageType为文件夹类型时)
            if page_type in (1, "1", 2, "2"):  # 文件夹类型
                sub_id = p.get("id") or p.get("pageId")
                if sub_id:
                    results.extend(_scan_folder_api(client, team_id, sub_id, depth+1, max_depth, visited))
    except Exception as e:
        print(f"  [WARN] 扫描文件夹 {folder_id} 失败: {e}")
    return results


def scan_folder_recursive(client, params: dict) -> dict:
    """递归扫描文件夹下所有文档(API方式, 无需Playwright)。

    params: team_id(可选), folder_id(必填), max_depth(可选,默认30)
    返回: {pages: [...], total}
    """
    team_id = params.get("team_id") or client._team_id
    folder_id = params.get("folder_id") or params.get("folderId")
    max_depth = params.get("max_depth", 30)
    if not folder_id:
        raise RuntimeError("请指定 folder_id")
    print(f"[递归扫描] team={team_id}, folder={folder_id}, max_depth={max_depth}")
    pages = _scan_folder_api(client, team_id, folder_id, max_depth=max_depth)
    # 过滤掉文件夹本身,只留文档
    docs = [p for p in pages if p["pageType"] not in (1, "1", 2, "2")]
    print(f"  共 {len(docs)} 个文档(含 {len(pages)-len(docs)} 个子文件夹)")
    return {"pages": docs, "total": len(docs)}


def _search_employee(client, erp: str):
    """搜索员工, 返回 {id, name, erp}。接口用 /v1/users/search (search参数, 非keyword)"""
    try:
        data = client.joyspace_get("/v1/users/search", params={"search": erp, "offset": "0", "length": "5"})
        # 响应结构: {data: {users: [{id, name, ...}]}} 或 {data: [...]}
        users = []
        d = data.get("data", {})
        if isinstance(d, dict):
            users = d.get("users") or d.get("list") or d.get("employees") or []
        elif isinstance(d, list):
            users = d
        if users and isinstance(users, list):
            e = users[0]
            return {"id": e.get("id") or e.get("userId") or e.get("uid"),
                    "name": e.get("name") or e.get("nickname") or erp,
                    "erp": erp}
    except Exception as e:
        print(f"  [WARN] 搜索员工 {erp} 失败: {e}")
    return None


def _execute_shares(client, page_user_map, deleted_pages=None):
    """执行静默权限开通。page_user_map: {pageId: [userId, ...]}"""
    if deleted_pages is None:
        deleted_pages = set()
    success, fail, skip = 0, 0, 0
    total = len(page_user_map)
    for i, (page_id, uids) in enumerate(page_user_map.items(), 1):
        if page_id in deleted_pages:
            skip += 1; continue
        unique_uids = list(set(uids))
        if not unique_uids:
            skip += 1; continue
        payload = {
            "page_id": page_id,
            "to_groups": [], "to_mail_groups": [], "to_orgs": [],
            "to_users": [{"id": uid, "permission_type": PERMISSION_TYPE} for uid in unique_uids],
            "content": "",
            "sendToChat": False, "watchComment": 0, "scene": "share",
            "notify": False, "silent": SHARE_SILENT, "sendNotification": False,
            "shouldNotify": False, "notifyAllCoops": False,
            "notifyUser": False, "skipNotification": SHARE_SKIP_NOTIFICATION,
        }
        try:
            result = client.joyspace_post("/v1/shares", payload)
            status = result.get("status", "") if isinstance(result, dict) else ""
            data = result.get("data", {}) if isinstance(result, dict) else {}
            total_shared = data.get("totalSharedUser", 0) if isinstance(data, dict) else 0
            if status == "success" and total_shared > 0:
                success += 1
                print(f"  ✅ [{i}/{total}] pageId={page_id} -> {total_shared} users")
            else:
                fail += 1
                print(f"  ❌ [{i}/{total}] pageId={page_id} status={status}")
        except Exception as e:
            fail += 1
            print(f"  ❌ [{i}/{total}] pageId={page_id} 异常: {e}")
    return {"success": success, "fail": fail, "skip": skip, "total": total}


def grant_folder_permissions(client, params: dict) -> dict:
    """批量给文件夹下所有文档开通权限(双模式确认架构, 借鉴joyspace-permission-grant)。

    params:
        team_id: 团队ID(可选)
        folder_id: 目标文件夹ID(必填)
        erps: 要开通权限的ERP列表(必填, 逗号分隔或数组)
        confirm: 是否执行权限开通(False=prepare模式只生成计划, True=confirm模式执行)
        max_depth: 递归深度(默认30)
    """
    team_id = params.get("team_id") or client._team_id
    folder_id = params.get("folder_id") or params.get("folderId")
    erps = params.get("erps") or params.get("erps_list") or []
    if isinstance(erps, str):
        erps = [e.strip() for e in erps.split(",") if e.strip()]
    confirm = params.get("confirm", False)
    max_depth = params.get("max_depth", 30)

    if not folder_id:
        raise RuntimeError("请指定 folder_id")
    if not erps:
        raise RuntimeError("请指定 erps (要开通权限的ERP列表)")

    # 双模式架构: prepare模式强制不执行权限开通
    if not confirm:
        print(f"[prepare模式] 仅生成权限计划, 不执行开通(需 confirm=True 才执行)")
    else:
        print(f"[confirm模式] 将执行静默权限开通")

    print(f"  team={team_id}, folder={folder_id}, erps={erps}")

    # 1. 搜索员工拿userId
    print("  Step 1: 解析ERP→userId...")
    user_ids = []
    erp_uid_map = {}
    for erp in erps:
        emp = _search_employee(client, erp)
        if emp and emp["id"]:
            user_ids.append(emp["id"])
            erp_uid_map[erp] = emp["id"]
            print(f"    {erp} -> {emp['id']} ({emp['name']})")
        else:
            print(f"    {erp} -> 未找到")
    if not user_ids:
        raise RuntimeError("未找到任何有效用户,无法继续")

    # 2. 递归扫描文件夹
    print("  Step 2: 递归扫描文件夹下所有文档...")
    pages = _scan_folder_api(client, team_id, folder_id, max_depth=max_depth)
    docs = [p for p in pages if p["pageType"] not in (1, "1", 2, "2")]
    print(f"    共 {len(docs)} 个文档")

    # 3. 构造权限计划
    page_user_map = {p["pageId"]: user_ids for p in docs}
    plan = {
        "folder_id": folder_id, "team_id": team_id, "erps": erps,
        "user_ids": user_ids, "erp_uid_map": erp_uid_map,
        "page_count": len(docs),
        "pages": [{"pageId": p["pageId"], "title": p["title"]} for p in docs],
    }

    # 4. prepare模式: 只生成计划,强制不执行(借鉴双模式确认架构)
    if not confirm:
        print(f"\n  ✅ 权限计划已生成: {len(docs)}个文档 × {len(user_ids)}个用户 = {len(docs)*len(user_ids)}条权限")
        print(f"  ⚠️ prepare模式不执行开通。确认无误后用 confirm=true 重新调用执行")
        return {"mode": "prepare", "plan": plan, "executed": False,
                "page_count": len(docs), "user_count": len(user_ids)}

    # 5. confirm模式: 执行静默权限开通
    print(f"\n  Step 3: 执行静默权限开通(POST /v1/shares, permission_type={PERMISSION_TYPE} Reader)...")
    result = _execute_shares(client, page_user_map)
    print(f"\n  ✓ 开通完成: 成功{result['success']}, 失败{result['fail']}, 跳过{result['skip']}, 总计{result['total']}")
    return {"mode": "confirm", "executed": True, "result": result, "plan": plan}
