from fastapi import APIRouter, Depends, Query, Request
from ...core.database import get_db, get_system_db, _has_split_databases
from ...core.permission import require_login
from ...utils.request_utils import safe_json

router = APIRouter()


async def get_system_db_dep():
    """FastAPI 依赖：优先使用 system.db，单库模式回退到 get_db()"""
    _db_gen = get_system_db() if _has_split_databases() else get_db()
    async for db in _db_gen:
        yield db

TEMPLATE_CATEGORIES = {
    "案件来源类": "case_source",
    "立案类": "case_filing",
    "调查取证类": "investigation",
    "强制措施类": "enforcement_measures",
    "先行处置类": "prior_disposal",
    "检验检测类": "inspection",
    "审核告知类": "review_notice",
    "决定类": "decision",
    "执行类": "execution",
    "结案归档类": "closing",
    "投诉举报类": "complaint",
}


@router.get("")
async def list_templates(
    request: Request,
    page: int = Query(1, ge=1),
    pageSize: int = Query(20, ge=1, le=200),
    category: str = Query(""),
    keyword: str = Query(""),
    layout: str = Query(""),
    user: dict = Depends(require_login),
    db=Depends(get_system_db_dep),
):
    conn, cur = db

    conditions = ["is_deleted = 0", "is_active = 1"]
    params: list = []

    if category:
        conditions.append("template_category = %s")
        params.append(category)

    if keyword:
        conditions.append("(template_name LIKE %s OR template_code LIKE %s OR description LIKE %s)")
        params.extend([f"%{keyword}%", f"%{keyword}%", f"%{keyword}%"])

    if layout:
        conditions.append("JSON_EXTRACT(schema_json, '$.layout') = %s")
        params.append(layout)

    where = f"WHERE {' AND '.join(conditions)}"

    await cur.execute(f"SELECT COUNT(*) as total FROM document_templates {where}", params)
    total = (await cur.fetchone())["total"]

    offset = (page - 1) * pageSize
    await cur.execute(
        f"SELECT id, template_code, template_name, template_category, template_type, "
        f"description, version, preview_image_path, layout_type, "
        f"is_system, is_active, usage_count, created_at, updated_at "
        f"FROM document_templates {where} ORDER BY template_category, template_type ASC LIMIT %s OFFSET %s",
        params + [pageSize, offset],
    )
    rows = [dict(row) for row in (await cur.fetchall())]

    for row in rows:
        row["category_key"] = TEMPLATE_CATEGORIES.get(row.get("template_category"), row.get("template_category"))

    return {"list": rows, "total": total, "page": page, "pageSize": pageSize, "categories": TEMPLATE_CATEGORIES}


@router.get("/categories")
async def get_template_categories(
    request: Request,
    user: dict = Depends(require_login),
    db=Depends(get_system_db_dep),
):
    return {"categories": TEMPLATE_CATEGORIES}


@router.get("/{id}")
async def get_template(
    id: int,
    request: Request,
    user: dict = Depends(require_login),
    db=Depends(get_system_db_dep),
):
    conn, cur = db

    await cur.execute(
        "SELECT * FROM document_templates WHERE id = %s AND is_deleted = 0",
        (id,),
    )
    row = await cur.fetchone()
    if not row:
        return {"error": "模板不存在", "detail": "template not found"}

    return dict(row)


@router.get("/{id}/download")
async def download_template(
    id: int,
    request: Request,
    user: dict = Depends(require_login),
    db=Depends(get_system_db_dep),
):
    conn, cur = db

    await cur.execute(
        "SELECT id, template_name, template_file_path FROM document_templates WHERE id = %s AND is_deleted = 0",
        (id,),
    )
    row = await cur.fetchone()
    if not row:
        return {"error": "模板不存在", "detail": "template not found"}

    await cur.execute(
        "UPDATE document_templates SET usage_count = usage_count + 1 WHERE id = %s",
        (id,),
    )

    return dict(row)


@router.post("/download/batch")
async def batch_download_templates(
    request: Request,
    user: dict = Depends(require_login),
    db=Depends(get_system_db_dep),
):
    body = await safe_json(request)
    ids = body.get("ids", [])

    if not ids:
        return {"error": "请选择要下载的模板", "detail": "ids required"}

    conn, cur = db
    placeholders = ",".join(["%s"] * len(ids))
    await cur.execute(
        f"SELECT id, template_name, template_file_path FROM document_templates WHERE id IN ({placeholders}) AND is_deleted = 0",
        ids,
    )
    rows = [dict(row) for row in (await cur.fetchall())]

    return {"templates": rows}
