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

router = APIRouter()


async def _system_db():
    """Dependency: system.db when split databases exist, otherwise fallback to get_db()"""
    _db_gen = get_system_db() if _has_split_databases() else get_db()
    async for conn, cur in _db_gen:
        yield conn, cur


@router.get("")
async def list_quick_prompts(
    request: Request,
    page: int = Query(1, ge=1),
    pageSize: int = Query(25, ge=1, le=100),
    keyword: str = Query(""),
    db=Depends(_system_db),
):
    current_user = get_current_user(request)
    if not current_user:
        return {"error": "未登录", "detail": "unauthorized"}

    conn, cur = db

    where = "WHERE 1=1"
    params = []

    if keyword:
        where += " AND (label LIKE %s OR template LIKE %s)"
        params.extend([f"%{keyword}%", f"%{keyword}%"])

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

    offset = (page - 1) * pageSize
    await cur.execute(
        f"SELECT * FROM quick_prompts {where} ORDER BY sort_order ASC, id ASC LIMIT %s OFFSET %s",
        params + [pageSize, offset],
    )
    rows = await cur.fetchall()
    items = [dict(r) for r in rows]

    return {"list": items, "total": total, "page": page, "pageSize": pageSize}


@router.get("/{item_id}")
async def get_quick_prompt(item_id: int, request: Request, db=Depends(_system_db)):
    current_user = get_current_user(request)
    if not current_user:
        return {"error": "未登录", "detail": "unauthorized"}

    conn, cur = db
    await cur.execute("SELECT * FROM quick_prompts WHERE id = %s", (item_id,))
    row = await cur.fetchone()
    if not row:
        return {"error": "快捷提问不存在", "detail": "quick prompt not found"}

    return dict(row)


@router.post("")
async def create_quick_prompt(request: Request, db=Depends(_system_db)):
    current_user = get_current_user(request)
    if not current_user:
        return {"error": "未登录", "detail": "unauthorized"}

    if not is_admin_role(current_user["role"]):
        return {"error": "无权限，仅管理员可创建快捷提问", "detail": "admin required"}

    conn, cur = db
    body = await safe_json(request)
    label = body.get("label", "").strip()
    template = body.get("template", "").strip()
    icon = body.get("icon", "").strip()
    sort_order = body.get("sort_order", 0)

    if not label:
        return {"error": "标签不能为空", "detail": "label required"}
    if not template:
        return {"error": "提问模板不能为空", "detail": "template required"}

    await cur.execute(
        "INSERT INTO quick_prompts (label, icon, template, sort_order) VALUES (%s, %s, %s, %s)",
        (label, icon, template, sort_order),
    )

    return {"success": True, "message": "快捷提问创建成功"}


@router.put("/{item_id}")
async def update_quick_prompt(item_id: int, request: Request, db=Depends(_system_db)):
    current_user = get_current_user(request)
    if not current_user:
        return {"error": "未登录", "detail": "unauthorized"}

    if not is_admin_role(current_user["role"]):
        return {"error": "无权限，仅管理员可修改快捷提问", "detail": "admin required"}

    conn, cur = db
    await cur.execute("SELECT id FROM quick_prompts WHERE id = %s", (item_id,))
    if not await cur.fetchone():
        return {"error": "快捷提问不存在", "detail": "quick prompt not found"}

    body = await safe_json(request)
    label = body.get("label", "").strip()
    template = body.get("template", "").strip()
    icon = body.get("icon", "").strip()
    sort_order = body.get("sort_order")

    updates = []
    params = []

    if label:
        updates.append("label = %s")
        params.append(label)
    if icon is not None:
        updates.append("icon = %s")
        params.append(icon)
    if template:
        updates.append("template = %s")
        params.append(template)
    if sort_order is not None:
        updates.append("sort_order = %s")
        params.append(sort_order)

    if not updates:
        return {"error": "无更新内容", "detail": "no fields to update"}

    updates.append("updated_at = CURRENT_TIMESTAMP")
    params.append(item_id)

    await cur.execute(
        f"UPDATE quick_prompts SET {', '.join(updates)} WHERE id = %s",
        params,
    )

    return {"success": True, "message": "快捷提问更新成功"}


@router.delete("/{item_id}")
async def delete_quick_prompt(item_id: int, request: Request, db=Depends(_system_db)):
    current_user = get_current_user(request)
    if not current_user:
        return {"error": "未登录", "detail": "unauthorized"}

    if not is_admin_role(current_user["role"]):
        return {"error": "无权限，仅管理员可删除快捷提问", "detail": "admin required"}

    conn, cur = db
    await cur.execute("SELECT id FROM quick_prompts WHERE id = %s", (item_id,))
    if not await cur.fetchone():
        return {"error": "快捷提问不存在", "detail": "quick prompt not found"}

    await cur.execute("DELETE FROM quick_prompts WHERE id = %s", (item_id,))

    return {"success": True, "message": "快捷提问删除成功"}


@router.put("/{item_id}/toggle")
async def toggle_quick_prompt(item_id: int, request: Request, db=Depends(_system_db)):
    current_user = get_current_user(request)
    if not current_user:
        return {"error": "未登录", "detail": "unauthorized"}

    if not is_admin_role(current_user["role"]):
        return {"error": "无权限，仅管理员可切换快捷提问状态", "detail": "admin required"}

    conn, cur = db
    await cur.execute("SELECT enabled FROM quick_prompts WHERE id = %s", (item_id,))
    row = await cur.fetchone()
    if not row:
        return {"error": "快捷提问不存在", "detail": "quick prompt not found"}

    new_enabled = 0 if dict(row)["enabled"] else 1
    await cur.execute(
        "UPDATE quick_prompts SET enabled = %s, updated_at = CURRENT_TIMESTAMP WHERE id = %s",
        (new_enabled, item_id),
    )

    return {"success": True, "message": "快捷提问状态已更新", "enabled": bool(new_enabled)}
