import os
import io
import zipfile
import logging

logger = logging.getLogger(__name__)

from fastapi import APIRouter, HTTPException, Body, Query, Request
from fastapi.responses import FileResponse, StreamingResponse

from sqlalchemy import select

from config import WIKI_DIR, BASE_DIR
from src.database.models import WikiKbInfo, WikiOaDept
from src.database.session import AsyncSessionLocal
from src.services.identity.tokens import get_current_user_optional
from src.services.oa import enums
from src.services.oa.kb_paths import kb_wiki_dir
from src.services.oa.kb_provision import is_builtin_kb
from src.services.oa.perms import resolve_readable_kbs

router = APIRouter()


async def _resolve_readable_wiki_dir(kb_id: str, request: Request) -> str:
    """据 kbId 返回该库 wiki 目录(空=内置库)。其余库校验当前用户可读,否则 403。(供 /wiki/tree 用)

    放行条件按「是否内置库」而非 kb_type:内置库对应全局 ware/wiki,与下面 _readable_wiki_dirs
    的「恒可读」保持一致;其它公共库只是权限语义为公共,读权限仍须经授权,否则把某库改成
    公共库就等于绕过授权把它的页面对全员放开。
    """
    if not kb_id:
        return WIKI_DIR
    async with AsyncSessionLocal() as session:
        kb = await session.get(WikiKbInfo, kb_id)
    if kb is None or kb.del_flag != enums.DEL_NORMAL:
        raise HTTPException(status_code=404, detail="知识库不存在")
    if not is_builtin_kb(kb):
        user = await get_current_user_optional(request)
        if user is None:
            raise HTTPException(status_code=403, detail="未登录,无法访问该知识库")
        readable = await resolve_readable_kbs(user)
        if kb.id not in {k.id for k in readable}:
            raise HTTPException(status_code=403, detail="无该知识库的读取权限")
    return kb_wiki_dir(kb)


async def _readable_wiki_dirs(request: Request) -> list[str]:
    """当前用户可读的全部 wiki 目录(绝对路径):公共基础库 + 可读部门库。

    file/download 的 path 为**项目根相对路径**(如 ware/wiki/... 或 ware/kb/dept/<id>/wiki/...),
    据此集合校验目标是否落在任一可读库内,避免越权读取其它库。
    """
    dirs = {os.path.abspath(WIKI_DIR)}  # base 恒可读
    user = await get_current_user_optional(request)
    if user is not None:
        for kb in await resolve_readable_kbs(user):
            dirs.add(os.path.abspath(kb_wiki_dir(kb)))
    return list(dirs)


def _resolve_project_rel_target(path: str, readable_dirs: list[str]) -> str:
    """把项目根相对路径解析为绝对路径,并校验落在某个可读 wiki 目录内;否则抛错。"""
    target = os.path.abspath(os.path.join(BASE_DIR, path))
    for d in readable_dirs:
        if target == d or target.startswith(d + os.sep):
            return target
    raise HTTPException(status_code=403, detail="无该文件所在知识库的读取权限")


@router.get("/wiki/content/{name}")
async def get_wiki_content(name: str):
    """从 wiki 子目录中查找并返回特定页面的 Markdown 内容。"""
    logger.info(f"请求查看 Wiki 页面内容: name={name}")
    for root, dirs, files in os.walk(WIKI_DIR):
        if name in files or f"{name}.md" in files:
            target = os.path.join(root, name if name.endswith(".md") else f"{name}.md")
            with open(target, "r", encoding="utf-8", errors="replace") as f:
                return {"content": f.read()}
    raise HTTPException(status_code=404, detail="Wiki page not found")


def _build_dir_tree(dir_path, rel_path=""):
    """把磁盘目录构建成 {name,type,path,children} 树;path 为项目根相对路径。"""
    tree = []
    try:
        items = os.listdir(dir_path)
    except Exception:
        return tree
    for item in sorted(items):
        full_path = os.path.join(dir_path, item)
        item_rel = os.path.join(rel_path, item).replace("\\", "/")
        if os.path.isdir(full_path):
            tree.append({"name": item, "type": "dir", "path": item_rel, "children": _build_dir_tree(full_path, item_rel)})
        else:
            tree.append({"name": item, "type": "file", "path": item_rel})
    return tree


async def _kb_label(kb_id: str) -> str:
    """库展示名(用作多库合并时的顶层文件夹名):部门库用组织路径,其余用库名。"""
    async with AsyncSessionLocal() as session:
        kb = await session.get(WikiKbInfo, kb_id)
        if kb is None:
            return kb_id
        if kb.kb_type == enums.KB_DEPT and kb.dept_id:
            depts = {d.id: d for d in (
                await session.execute(select(WikiOaDept).where(WikiOaDept.del_flag == enums.DEL_NORMAL))
            ).scalars().all()}
            d = depts.get(kb.dept_id)
            if d is not None:
                chain = [depts[p] for p in (d.ancestors or "").split(",") if p in depts] + [d]
                return " / ".join(x.dept_name for x in chain)
        return kb.kb_name


@router.get("/wiki/tree")
async def get_wiki_tree(
    request: Request,
    kb_id: str = Query("", alias="kbId"),
    kb_ids: str = Query("", alias="kbIds"),
):
    """返回知识库 wiki 目录树(kbId 空=公共基础库)。

    kbIds(逗号分隔)=一次看多个库(选某中心=其下全部库):每个库合并为一层顶层文件夹,
    文件夹名用库的组织路径 / 库名,子树仍是项目根相对路径,与 file/download 约定一致。
    """
    ids = [i for i in (kb_ids.split(",") if kb_ids else []) if i.strip()]
    if not ids and kb_id:
        ids = [kb_id]
    ids = list(dict.fromkeys(ids))  # 去重保序
    logger.info("请求获取 Wiki 目录树 ids=%s", ids)

    # 单库(或未指定):直接返回该库目录内容(保持原行为)
    if len(ids) <= 1:
        wiki_base = await _resolve_readable_wiki_dir(ids[0] if ids else "", request)
        wiki_rel = os.path.relpath(wiki_base, BASE_DIR).replace("\\", "/")
        return {"tree": _build_dir_tree(wiki_base, wiki_rel)}

    # 多库:每个库包一层顶层文件夹合并成森林
    forest = []
    for kid in ids:
        wiki_base = await _resolve_readable_wiki_dir(kid, request)  # 逐库校验可读
        wiki_rel = os.path.relpath(wiki_base, BASE_DIR).replace("\\", "/")
        forest.append({
            "name": await _kb_label(kid),
            "type": "dir",
            "path": wiki_rel,
            "children": _build_dir_tree(wiki_base, wiki_rel),
        })
    return {"tree": forest}


@router.get("/wiki/file")
async def get_wiki_file_by_path(request: Request, path: str):
    """读取 wiki 文件内容。path 为项目根相对路径,按当前用户可读库集合校验。"""
    if not path:
        raise HTTPException(status_code=400, detail="Path is required")

    readable_dirs = await _readable_wiki_dirs(request)
    target_path = _resolve_project_rel_target(path, readable_dirs)
    if not os.path.exists(target_path) or not os.path.isfile(target_path):
        raise HTTPException(status_code=404, detail="File not found")

    try:
        with open(target_path, "r", encoding="utf-8", errors="replace") as f:
            return {"content": f.read()}
    except Exception as e:
        logger.error(f"读取 Wiki 文件失败 [{path}]: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/wiki/download")
async def download_wiki_file(request: Request, path: str):
    """下载单个 wiki 文件。path 为项目根相对路径,按可读库集合校验。"""
    logger.info(f"请求下载单个 Wiki 文件: path={path}")
    if not path:
        raise HTTPException(status_code=400, detail="Path is required")
    readable_dirs = await _readable_wiki_dirs(request)
    target_path = _resolve_project_rel_target(path, readable_dirs)
    if not os.path.exists(target_path) or not os.path.isfile(target_path):
        raise HTTPException(status_code=404, detail="File not found")

    return FileResponse(target_path, filename=os.path.basename(target_path))


@router.post("/wiki/download_batch")
async def download_wiki_batch(request: Request, data: dict = Body(...)):
    """批量下载 wiki 文件,返回 ZIP。paths 为项目根相对路径,逐个按可读库校验。"""
    paths = data.get("paths", [])
    logger.info(f"请求批量下载 Wiki 文件,涉及路径数量: {len(paths)}")
    if not paths:
        raise HTTPException(status_code=400, detail="No paths provided")

    readable_dirs = await _readable_wiki_dirs(request)
    zip_buffer = io.BytesIO()
    with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zip_file:
        for p in paths:
            try:
                target_path = _resolve_project_rel_target(p, readable_dirs)
            except HTTPException:
                continue
            if os.path.isfile(target_path):
                zip_file.write(target_path, arcname=os.path.basename(p))

    zip_buffer.seek(0)
    return StreamingResponse(
        zip_buffer,
        media_type="application/zip",
        headers={"Content-Disposition": "attachment; filename=wiki_export.zip"}
    )