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

router = APIRouter()


@router.get("")
async def list_cases(
    request: Request,
    limit: int = Query(20, ge=1, le=100),
    offset: int = Query(0, ge=0),
    db=Depends(get_db),
):
    current_user = get_current_user(request)
    if not current_user or not is_admin_role(current_user["role"]):
        return {"error": "无权限", "detail": "admin required"}

    conn, cur = db
    try:
        await cur.execute(
            """SELECT c.*, u.username as owner_name
             FROM cases c LEFT JOIN users u ON c.created_by = u.id
             ORDER BY c.updated_at DESC LIMIT %s OFFSET %s""",
            (limit, offset),
        )
        rows = await cur.fetchall()

        await cur.execute("SELECT COUNT(*) as total FROM cases")
        total = dict(await cur.fetchone())["total"]

        return {"cases": [dict(r) for r in rows], "total": total}
    except Exception:
        return {"cases": [], "total": 0}


@router.post("")
async def case_action(request: Request, db=Depends(get_db)):
    current_user = get_current_user(request)
    if not current_user or not is_admin_role(current_user["role"]):
        return {"error": "无权限", "detail": "admin required"}

    body = await safe_json(request)
    action = body.get("action")

    if action == "create_thread":
        case_id = body.get("case_id")
        if not case_id:
            return {"error": "缺少案件ID", "detail": "case_id required"}

        conn, cur = db
        thread_title = body.get("thread_title")
        thread_purpose = body.get("thread_purpose")
        agent_id = body.get("agent_id")

        try:
            await cur.execute(
                """INSERT INTO case_threads (case_id, thread_id, agent_id, thread_title, thread_purpose, is_active, created_by)
                   VALUES (%s, %s, %s, %s, %s, 1, %s)""",
                (case_id, f"thread-{case_id}-{__import__('time').time()}", agent_id, thread_title, thread_purpose, current_user.get("userId")),
            )

            try:
                await cur.execute("UPDATE cases SET threads_count = threads_count + 1, last_activity_at = NOW() WHERE id = %s", (case_id,))
            except Exception:
                pass

            return {"success": True, "thread_id": f"thread-{case_id}", "message": "案件会话创建成功"}
        except Exception as e:
            if "1146" in str(e) or "doesn't exist" in str(e):
                return {"error": "案件表尚未创建", "detail": "table not created yet"}
            raise

    return {"error": "不支持的操作类型", "detail": "unsupported action"}
