"""
JoySpace 文件管理 —— 上传/下载/列出文件（借鉴 joyspace-upload skill）。

能力：
- upload_file: 上传本地文件(Excel/图片/附件)到 JoySpace 团队空间(WPS v3 分片上传)
- download_file: 下载在线文件为本地 xlsx(导出+轮询)
- list_files: 列出文件夹下的文件(补充 list_folder_children 只列文档不列附件的缺口)

移植自 joyspace-upload.mjs (Node.js)，适配到 joyspace-pro 的 JoySpaceClient。
"""

import json
import os
import time
from pathlib import Path

import requests

# 平台常量(与 joyspace-upload config.json 一致)
JOYSPACE_API = "https://apijoyspace.jd.com"
PART_SIZE = 16 * 1024 * 1024  # 16MB 分片
MAX_RETRIES = 3
EXPORT_TYPE = "xlsx"

# 走 WPS/MinIO (v3) 上传的 Office 文档类型；其余(图片/压缩包)走 EEFS (v1)
OFFICE_EXTS = {".doc", ".docx", ".ppt", ".pptx", ".xls", ".xlsx", ".pdf"}


def _mimeTypeOf(filename: str) -> str:
    ext = Path(filename).suffix.lower()
    return {
        ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        ".xls": "application/vnd.ms-excel",
        ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        ".doc": "application/msword",
        ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
        ".ppt": "application/vnd.ms-powerpoint",
        ".pdf": "application/pdf",
        ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
        ".gif": "image/gif", ".zip": "application/zip",
    }.get(ext, "application/octet-stream")


def _pageTypeOf(filename: str) -> int:
    """文件→页面类型: 5=sheet, 6=word, 7=ppt, 9=附件, 11=pdf"""
    ext = Path(filename).suffix.lower()
    return {".xlsx": 5, ".xls": 5, ".doc": 6, ".docx": 6,
            ".ppt": 7, ".pptx": 7, ".pdf": 11}.get(ext, 9)


def _isOfficeFile(filename: str) -> bool:
    return Path(filename).suffix.lower() in OFFICE_EXTS


def _fetch_with_retry(url, opts, retries=MAX_RETRIES):
    """requests 版的 fetchWithRetry"""
    last_err = None
    for i in range(retries):
        try:
            method = opts.get("method", "GET")
            if method == "GET":
                r = requests.get(url, headers=opts.get("headers"), timeout=opts.get("timeout", 120),
                                 params=opts.get("params"))
            elif method == "PUT":
                r = requests.put(url, headers=opts.get("headers"), data=opts.get("body"),
                                  timeout=opts.get("timeout", 120))
            elif method == "POST":
                r = requests.post(url, headers=opts.get("headers"), json=opts.get("json"),
                                  data=opts.get("body"), timeout=opts.get("timeout", 120))
            else:
                r = requests.request(method, url, headers=opts.get("headers"), timeout=opts.get("timeout", 120))
            return r
        except requests.RequestException as e:
            last_err = e
            time.sleep(1 + i)
    raise last_err


def upload_file(client, params: dict) -> dict:
    """上传本地文件到 JoySpace 团队空间(WPS v3 分片上传)。

    params:
        file: 本地文件路径(必填)
        team_id: 团队ID(可选,默认用client的)
        folder_id: 目标文件夹ID(必填)
    返回: {pageId, fileId, title}
    """
    file_path = params.get("file") or params.get("filePath")
    team_id = params.get("team_id") or client._team_id
    folder_id = params.get("folder_id") or params.get("folderId")
    if not file_path or not os.path.exists(file_path):
        raise RuntimeError(f"文件不存在: {file_path}")
    if not folder_id:
        raise RuntimeError("请指定 folder_id (目标文件夹ID)")

    abs_path = os.path.abspath(file_path)
    file_name = os.path.basename(abs_path)
    file_size = os.path.getsize(abs_path)
    mime_type = _mimeTypeOf(file_name)

    print(f"[上传] {file_name} ({file_size/1024:.1f}KB, {mime_type})")
    print(f"  目标: team={team_id}, folder={folder_id}")

    headers = client._joyspace_headers()

    # Step 1: 初始化上传
    print("  Step 1/4: 初始化上传...")
    init_res = _fetch_with_retry(f"{JOYSPACE_API}/v3/web-files/init", {
        "method": "POST", "headers": {**headers, "Content-Type": "application/json"},
        "json": {"fileName": file_name, "fileSize": file_size, "mimeType": mime_type},
    })
    if init_res.status_code != 200:
        raise RuntimeError(f"初始化上传失败: HTTP {init_res.status_code} {init_res.text[:200]}")
    init_data = init_res.json()
    init_data = init_data.get("data", init_data)
    upload_id = init_data.get("uploadId") or init_data.get("upload_id")
    part_infos = init_data.get("partInfos") or init_data.get("part_infos") or []
    if not part_infos:
        raise RuntimeError(f"初始化上传未返回 partInfos: {json.dumps(init_data, ensure_ascii=False)[:200]}")
    print(f"  uploadId: {upload_id}, 分片数: {len(part_infos)}")

    # Step 2: 分片上传到 MinIO
    print("  Step 2/4: 上传文件内容到 MinIO...")
    upload_results = []
    with open(abs_path, "rb") as f:
        for part in part_infos:
            part_number = part.get("partNumber") or part.get("part_number")
            upload_url = part.get("uploadUrl") or part.get("upload_url")
            part_headers = part.get("headers") or {}
            start = (part_number - 1) * PART_SIZE
            f.seek(start)
            chunk = f.read(PART_SIZE)
            print(f"    分片 {part_number}: {start}-{start+len(chunk)} ({len(chunk)} bytes)")

            put_headers = dict(part_headers)
            if "Content-Type" not in put_headers and "content-type" not in put_headers:
                put_headers["Content-Type"] = "application/octet-stream"
            put_res = _fetch_with_retry(upload_url, {
                "method": "PUT", "headers": put_headers, "body": chunk,
            })
            if put_res.status_code not in (200, 204):
                raise RuntimeError(f"分片 {part_number} 上传失败: HTTP {put_res.status_code} {put_res.text[:200]}")
            wps_token = put_res.headers.get("x-wps3-info-token", "")
            upload_results.append({"partNumber": part_number, "wpsToken": wps_token})
            print(f"    分片 {part_number} 完成, token: {wps_token[:30]+'...' if wps_token else '(无)'}")

    # Step 3: 完成上传
    print("  Step 3/4: 确认上传完成...")
    complete_body = {
        "uploadId": upload_id,
        "parts": [
            {"partNumber": r["partNumber"],
             "storeResponseInfos": [{"name": "X-Wps3-Info-Token", "value": r["wpsToken"]}] if r["wpsToken"] else []}
            for r in upload_results
        ],
    }
    complete_res = _fetch_with_retry(f"{JOYSPACE_API}/v3/web-files/complete", {
        "method": "POST", "headers": {**headers, "Content-Type": "application/json"},
        "json": complete_body,
    })
    if complete_res.status_code != 200:
        raise RuntimeError(f"完成上传失败: HTTP {complete_res.status_code} {complete_res.text[:200]}")
    complete_data = complete_res.json().get("data", {})
    relate_file_id = complete_data.get("fileId") or complete_data.get("id") or ""
    print(f"  fileId: {relate_file_id}")

    # Step 4: 创建页面
    print("  Step 4/4: 创建页面...")
    page_type = _pageTypeOf(file_name)
    create_body = {
        "title": file_name, "fileType": page_type, "relateFileId": relate_file_id,
        "folderId": folder_id, "teamId": team_id,
    }
    create_res = _fetch_with_retry(f"{JOYSPACE_API}/v2/pages", {
        "method": "POST", "headers": {**headers, "Content-Type": "application/json"},
        "json": create_body,
    })
    if create_res.status_code != 200:
        raise RuntimeError(f"创建页面失败: HTTP {create_res.status_code} {create_res.text[:200]}")
    create_data = create_res.json().get("data", {})
    page_id = create_data.get("id") or create_data.get("pageId") or ""
    print(f"  ✓ 上传成功! pageId: {page_id}")
    return {"pageId": page_id, "fileId": relate_file_id, "title": file_name}


def download_file(client, params: dict) -> dict:
    """下载在线文件为本地 xlsx(导出+轮询)。

    params:
        page_id: 页面ID(必填) 或 url: joyspace.jd.com/sheets/xxx
        team_id: 团队ID(可选)
        output_dir: 输出目录(可选,默认当前目录)
    返回: {file: 文件路径, title}
    """
    page_id = params.get("page_id") or params.get("pageId")
    url = params.get("url")
    if not page_id and url:
        # 从url解析pageId
        import re
        m = re.search(r"/(sheets|pages|doc)/([a-zA-Z0-9]+)", url)
        if m: page_id = m.group(2)
    if not page_id:
        raise RuntimeError("请指定 page_id 或 url")
    team_id = params.get("team_id") or client._team_id
    output_dir = params.get("output_dir") or params.get("outputDir") or "."
    headers = client._joyspace_headers()

    # Step 1: 获取页面信息
    print(f"[下载] pageId={page_id}")
    print("  Step 1/3: 获取文件信息...")
    basic_res = _fetch_with_retry(f"{JOYSPACE_API}/v2/pages/{page_id}/basic", {
        "method": "GET", "headers": headers,
    })
    if basic_res.status_code != 200:
        raise RuntimeError(f"获取页面信息失败: HTTP {basic_res.status_code}")
    basic_data = basic_res.json().get("data", {})
    file_name = basic_data.get("title") or "downloaded_file"
    page_type = basic_data.get("pageType")
    print(f"  文件: {file_name} (pageType={page_type})")

    # 根据文档类型选择导出格式: sheet(5)→xlsx, 其他(doc/mindmap等)→pdf
    # exportType: xlsx(仅sheet支持), pdf(通用), docx(仅word支持)
    export_type = params.get("export_type") or params.get("exportType") or EXPORT_TYPE
    if export_type == "xlsx" and page_type not in (5, "5", 9, "9"):
        # 非sheet文档xlsx会报"无效的导出类型", 自动改pdf
        export_type = "pdf"
        print(f"  文档类型非sheet, 自动改用pdf导出")
    print(f"  导出格式: {export_type}")

    # Step 2: 发起导出 + 轮询
    print("  Step 2/3: 发起导出...")
    export_res = _fetch_with_retry(f"{JOYSPACE_API}/v2/sm/export", {
        "method": "POST", "headers": {**headers, "Content-Type": "application/json"},
        "json": {"fileId": page_id, "title": file_name, "exportType": export_type},
    })
    if export_res.status_code != 200:
        raise RuntimeError(f"发起导出失败: HTTP {export_res.status_code}")
    export_data = export_res.json().get("data", {})
    task_id = export_data.get("taskId") or ""
    if not task_id:
        err = export_res.json().get("errMsg") or export_res.text[:200]
        raise RuntimeError(f"导出未返回 taskId: {err}")
    print(f"  taskId: {task_id}")

    print("  轮询导出进度...")
    download_url = ""
    for i in range(30):
        time.sleep(1)
        poll_res = _fetch_with_retry(f"{JOYSPACE_API}/v2/sm/getExportProcess", {
            "method": "POST", "headers": {**headers, "Content-Type": "application/json"},
            "json": {"fileId": page_id, "taskId": task_id},
        })
        if poll_res.status_code != 200:
            continue
        result = poll_res.json().get("data", {})
        status = result.get("status") or result.get("processStatus") or ""
        download_url = result.get("downloadUrl") or result.get("url") or result.get("fileUrl") or ""
        print(f"    [{i+1}/30] status={status}")
        if download_url or status in ("完成", "done", "success", "3"):
            break
    if not download_url:
        raise RuntimeError("导出超时,未获取到下载URL")

    # Step 3: 下载文件
    print("  Step 3/3: 下载文件...")
    os.makedirs(output_dir, exist_ok=True)
    safe_name = "".join(c for c in file_name if c not in '<>:"/\\|?*')[:50]
    out_file = os.path.join(output_dir, f"{safe_name}.{export_type}")
    dl_res = requests.get(download_url, headers={"Cookie": client._cookies()}, timeout=120)
    if dl_res.status_code != 200:
        raise RuntimeError(f"下载失败: HTTP {dl_res.status_code}")
    with open(out_file, "wb") as f:
        f.write(dl_res.content)
    print(f"  ✓ 下载成功: {out_file} ({len(dl_res.content)/1024:.1f}KB)")
    return {"file": out_file, "title": file_name, "size": len(dl_res.content)}


def list_files(client, params: dict) -> dict:
    """列出文件夹下的文件(补充 list_folder_children 只列文档不列附件的缺口)。

    params:
        team_id: 团队ID(可选)
        folder_id: 文件夹ID(必填)
    返回: {files: [{title, pageType, pageId, updatedAt, creator}]}
    """
    team_id = params.get("team_id") or client._team_id
    folder_id = params.get("folder_id") or params.get("folderId")
    if not folder_id:
        raise RuntimeError("请指定 folder_id")
    headers = client._joyspace_headers()

    print(f"[列文件] team={team_id}, folder={folder_id}")
    url = f"{JOYSPACE_API}/v1/spaces/{team_id}/pages?categoryId={folder_id}&length=50&start=0&sort=-updated_at"
    res = _fetch_with_retry(url, {"method": "GET", "headers": headers})
    if res.status_code != 200:
        raise RuntimeError(f"列文件失败: HTTP {res.status_code}")
    data = res.json().get("data", {})
    pages = data.get("pages") or data.get("list") or data
    if not isinstance(pages, list):
        pages = []
    files = []
    for p in pages:
        files.append({
            "title": p.get("title") or "(未命名)",
            "pageType": p.get("pageType"),
            "pageId": p.get("id") or p.get("pageId"),
            "updatedAt": p.get("updatedAt") or p.get("updated_at"),
            "creator": (p.get("creator") or {}).get("name") if isinstance(p.get("creator"), dict) else p.get("creatorName", ""),
        })
    print(f"  共 {len(files)} 个文件:")
    for f in files:
        print(f"    [{f['pageType']}] {f['title']} (id={f['pageId']}, 更新={f['updatedAt']})")
    return {"files": files, "total": len(files)}
