import logging
from fastapi import APIRouter, Depends, Query, Request
from typing import Optional
from pydantic import BaseModel

from ...core.database import get_db, get_system_db, _has_split_databases
from ...core.permission import get_current_user

logger = logging.getLogger(__name__)

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


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


@router.get("/categories")
async def list_cause_categories(
    request: Request,
    db=Depends(get_system_db_dep),
):
    """获取案由分类列表（一级+二级）用于案件类型选择"""
    current_user = get_current_user(request)

    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 {
        'success': True,
        'data': {
            'list': list(categories.values()),
            'total_level1': len(categories),
            'total_level2': len(rows)
        }
    }


@router.get("")
async def list_enabled_causes(
    request: Request,
    db=Depends(get_system_db_dep),
    level1_code: Optional[str] = Query(None, description="一级案由代码"),
    level2_code: Optional[str] = Query(None, description="二级案由代码"),
):
    """获取启用的案由列表（三级案由）"""
    current_user = get_current_user(request)

    conn, cur = db

    conditions = ["c.is_enabled = 1"]
    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)

    where_clause = " AND ".join(conditions)

    await cur.execute(
        f"""SELECT id, cause_code, cause_name, cause_name_short,
               level1_code, level1_name, level2_code, level2_name,
               violation_law, penalty_law
        FROM case_causes c
        WHERE {where_clause}
        ORDER BY c.level1_code, c.level2_code, c.sort_num, c.id""",
        params,
    )
    rows = await cur.fetchall()

    causes = [dict(row) for row in rows]
    return {"success": True, "data": causes}


@router.get("/search")
async def search_causes(
    request: Request,
    db=Depends(get_system_db_dep),
    q: str = Query(..., min_length=1, description="搜索关键词"),
    limit: int = Query(10, ge=1, le=20),
):
    """搜索案由（三级案由）"""
    current_user = get_current_user(request)

    conn, cur = db

    search_pattern = f"%{q}%"
    await cur.execute(
        """SELECT id, cause_code, cause_name, cause_name_short,
               level1_code, level1_name, level2_code, level2_name,
               violation_law, penalty_law
        FROM case_causes
        WHERE is_enabled = 1
          AND (cause_name LIKE %s OR cause_code LIKE %s OR cause_name_short LIKE %s)
        ORDER BY level1_code, sort_num, id
        LIMIT %s""",
        [search_pattern, search_pattern, search_pattern, limit],
    )
    rows = await cur.fetchall()

    causes = [dict(row) for row in rows]
    return {"success": True, "data": causes}


class CreateCauseRequest(BaseModel):
    cause_name: str


@router.post("")
async def create_custom_cause(
    request: Request,
    body: CreateCauseRequest,
    db=Depends(get_system_db_dep),
):
    """保存自定义案由到数据库"""
    current_user = get_current_user(request)
    conn, cur = db

    cause_name = body.cause_name.strip()
    if not cause_name:
        return {"success": False, "error": "案由名称不能为空"}

    # 检查是否已存在
    await cur.execute(
        "SELECT id FROM case_causes WHERE cause_name = %s AND is_enabled = 1",
        (cause_name,),
    )
    existing = await cur.fetchone()
    if existing:
        return {"success": False, "error": "该案由已存在"}

    # 插入新案由（自定义案由不绑定分类，仅保存名称）
    import time as _time
    await cur.execute(
        """INSERT INTO case_causes
           (cause_code, cause_name, cause_name_short, is_enabled, sort_num)
           VALUES (%s, %s, %s, 1, 9999)""",
        (f"CUSTOM-{int(_time.time())}", cause_name, cause_name[:20] if len(cause_name) > 20 else cause_name),
    )
    new_id = cur.lastrowid
    await conn.commit()

    logger.info(f"用户 {current_user.get('userId')} 创建自定义案由: {cause_name} (id={new_id})")

    return {"success": True, "data": {"id": new_id, "cause_name": cause_name}}
