import logging
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from typing import Optional

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

logger = logging.getLogger(__name__)

router = APIRouter(tags=["admin-causes"])


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("/categories")
async def list_cause_categories(
    request: Request,
    db=Depends(_system_db),
):
    """获取案由分类列表（一级+二级）"""
    current_user = get_current_user(request)
    if not current_user or not is_admin_role(current_user.get("role", "")):
        return {"error": "无权限", "detail": "仅管理员可访问"}

    conn, cur = db
    
    await cur.execute("""
        SELECT 
            level1_code, level1_name, level1_sort,
            level2_code, level2_name, level2_sort,
            cause_count
        FROM case_cause_categories 
        ORDER BY level1_sort, level2_sort
    """)
    rows = await cur.fetchall()
    
    # 组织成层级结构
    categories = {}
    for row in rows:
        r = dict(row)
        l1_code = r['level1_code']
        
        if l1_code not in categories:
            categories[l1_code] = {
                'code': l1_code,
                'name': r['level1_name'],
                'sort': r['level1_sort'],
                'children': []
            }
        
        categories[l1_code]['children'].append({
            'code': r['level2_code'],
            'name': r['level2_name'],
            'sort': r['level2_sort'],
            'cause_count': r['cause_count']
        })
    
    return {
        'list': list(categories.values()),
        'total_level1': len(categories),
        'total_level2': len(rows)
    }


@router.get("")
async def list_causes(
    request: Request,
    db=Depends(_system_db),
    level1_code: Optional[str] = Query(None, description="一级案由代码"),
    level2_code: Optional[str] = Query(None, description="二级案由代码"),
    keyword: Optional[str] = Query(None),
    is_enabled: Optional[int] = Query(None),
    page: int = Query(1, ge=1),
    pageSize: int = Query(20, ge=1, le=100),
):
    """获取案由列表（支持三级分类筛选）"""
    current_user = get_current_user(request)
    if not current_user or not is_admin_role(current_user.get("role", "")):
        return {"error": "无权限", "detail": "仅管理员可访问"}

    conn, cur = db

    conditions = []
    params = []

    if level1_code:
        conditions.append("c.level1_code = %s")
        params.append(level1_code)
    if level2_code:
        conditions.append("c.level2_code = %s")
        params.append(level2_code)
    if keyword:
        conditions.append("(c.cause_name LIKE %s OR c.cause_code LIKE %s OR c.cause_name_short LIKE %s)")
        params.extend([f"%{keyword}%", f"%{keyword}%", f"%{keyword}%"])
    if is_enabled is not None:
        conditions.append("c.is_enabled = %s")
        params.append(is_enabled)

    where_clause = " AND ".join(conditions) if conditions else "1=1"

    await cur.execute(f"SELECT COUNT(*) as total FROM case_causes c WHERE {where_clause}", params)
    total = (await cur.fetchone())["total"]

    offset = (page - 1) * pageSize
    await cur.execute(
        f"""SELECT c.* FROM case_causes c
        WHERE {where_clause}
        ORDER BY c.level1_code, c.level2_code, c.sort_num, c.id
        LIMIT %s OFFSET %s""",
        params + [pageSize, offset],
    )
    rows = await cur.fetchall()

    causes = []
    for row in rows:
        cause = dict(row)
        if cause.get("created_at"):
            cause["created_at"] = cause["created_at"].isoformat() if hasattr(cause["created_at"], "isoformat") else str(cause["created_at"])
        if cause.get("updated_at"):
            cause["updated_at"] = cause["updated_at"].isoformat() if hasattr(cause["updated_at"], "isoformat") else str(cause["updated_at"])
        causes.append(cause)

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


@router.post("")
async def create_cause(
    request: Request,
    db=Depends(_system_db),
):
    """创建新案由"""
    current_user = get_current_user(request)
    if not current_user or not is_admin_role(current_user.get("role", "")):
        return {"error": "无权限", "detail": "仅管理员可操作"}

    body = await safe_json(request)
    cause_code = body.get("cause_code")
    cause_name = body.get("cause_name")

    if not cause_code or not cause_name:
        raise HTTPException(400, "案由编码和名称为必填项")

    conn, cur = db

    await cur.execute("SELECT id FROM case_causes WHERE cause_code = %s", (cause_code,))
    if await cur.fetchone():
        raise HTTPException(400, f"案由编码 {cause_code} 已存在")

    # 验证编码格式 (LL1-LL2-NNN)
    import re
    if not re.match(r'^\d{2}-\d{2}-\d{3}$', cause_code):
        raise HTTPException(400, "案由编码格式错误，应为 LL1-LL2-NNN 格式（如: 01-01-001）")

    await cur.execute(
        """INSERT INTO case_causes (
            cause_code, level1_code, level1_name, level2_code, level2_name,
            cause_name, cause_name_short, violation_law, penalty_law, remark, sort_num, is_enabled
        ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)""",
        (
            cause_code,
            body.get("level1_code"),
            body.get("level1_name"),
            body.get("level2_code"),
            body.get("level2_name"),
            cause_name,
            body.get("cause_name_short"),
            body.get("violation_law"),
            body.get("penalty_law"),
            body.get("remark"),
            body.get("sort_num", 0),
            body.get("is_enabled", 1),
        ),
    )
    new_id = cur.lastrowid

    return {"success": True, "data": {"id": new_id}, "message": "创建成功"}


@router.put("/{cause_id}")
async def update_cause(
    cause_id: int,
    request: Request,
    db=Depends(_system_db),
):
    """更新案由"""
    current_user = get_current_user(request)
    if not current_user or not is_admin_role(current_user.get("role", "")):
        return {"error": "无权限", "detail": "仅管理员可操作"}

    body = await safe_json(request)
    conn, cur = db

    await cur.execute("SELECT id FROM case_causes WHERE id = %s", (cause_id,))
    if not await cur.fetchone():
        raise HTTPException(404, "案由不存在")

    update_fields = []
    update_params = []
    for field in [
        "cause_code", "cause_name", "cause_name_short",
        "level1_code", "level1_name", "level2_code", "level2_name",
        "violation_law", "penalty_law", "remark",
        "sort_num", "is_enabled"
    ]:
        if field in body:
            update_fields.append(f"{field} = %s")
            update_params.append(body[field])

    if update_fields:
        update_params.append(cause_id)
        await cur.execute(
            f"UPDATE case_causes SET {', '.join(update_fields)}, updated_at = NOW() WHERE id = %s",
            update_params,
        )

    return {"success": True, "message": "更新成功"}


@router.delete("/{cause_id}")
async def delete_cause(
    cause_id: int,
    request: Request,
    db=Depends(_system_db),
):
    """删除案由"""
    current_user = get_current_user(request)
    if not current_user or not is_admin_role(current_user.get("role", "")):
        return {"error": "无权限", "detail": "仅管理员可删除"}

    conn, cur = db

    await cur.execute("SELECT id FROM case_causes WHERE id = %s", (cause_id,))
    if not await cur.fetchone():
        raise HTTPException(404, "案由不存在")

    await cur.execute("DELETE FROM case_causes WHERE id = %s", (cause_id,))

    # 更新分类统计
    await cur.execute("""
        UPDATE case_cause_categories cc
        SET cause_count = (
            SELECT COUNT(*) FROM case_causes c 
            WHERE c.level2_code = cc.level2_code
        )
        WHERE cc.level2_code IN (
            SELECT level2_code FROM case_causes WHERE id = %s
        )
    """, (cause_id,))

    return {"success": True, "message": "删除成功"}


@router.patch("/{cause_id}/toggle")
async def toggle_cause_enabled(
    cause_id: int,
    request: Request,
    db=Depends(_system_db),
):
    """切换案由启用状态"""
    current_user = get_current_user(request)
    if not current_user or not is_admin_role(current_user.get("role", "")):
        return {"error": "无权限", "detail": "仅管理员可操作"}

    conn, cur = db
    await cur.execute("SELECT id, is_enabled FROM case_causes WHERE id = %s", (cause_id,))
    row = await cur.fetchone()
    if not row:
        raise HTTPException(404, "案由不存在")

    new_status = 0 if row["is_enabled"] == 1 else 1
    await cur.execute(
        "UPDATE case_causes SET is_enabled = %s, updated_at = NOW() WHERE id = %s",
        (new_status, cause_id)
    )

    return {"success": True, "data": {"is_enabled": new_status}, "message": f"{'启用' if new_status else '禁用'}成功"}
