"""
处罚裁量规则查询 API

提供三层筛选（裁量类型 → 管理领域 → 违法事项关键词）查询裁量规则。
"""
from fastapi import APIRouter, Depends, Query, HTTPException
from typing import Optional

from ...core.database import get_db, get_system_db, _has_split_databases
from ...core.permission import require_login
from ...services.discretion_rule_service import (
    search_rules, get_domains, get_rule_by_id, get_source_files,
)

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


@router.get("/discretion-rules/sources")
async def list_source_files(
    user: dict = Depends(require_login),
    db=Depends(get_system_db_dep),
):
    """获取可用的裁量数据来源列表（不同地区的裁量清单）"""
    conn, cur = db
    sources = await get_source_files(conn, cur)
    return {"success": True, "data": {"list": sources}}


@router.get("/discretion-rules/domains")
async def list_domains(
    source_file: Optional[str] = Query(None, description="按数据来源过滤"),
    user: dict = Depends(require_login),
    db=Depends(get_system_db_dep),
):
    """获取管理领域下拉列表"""
    conn, cur = db
    domains = await get_domains(conn, cur, source_file=source_file)
    return {"success": True, "data": {"list": domains}}


@router.get("/discretion-rules/search")
async def search_discretion_rules(
    rule_type: Optional[str] = Query(None, description="裁量类型：从轻处罚/减轻处罚/不予处罚/免于强制措施"),
    domain: Optional[str] = Query(None, description="管理领域"),
    keyword: Optional[str] = Query(None, description="违法事项关键词"),
    source_file: Optional[str] = Query(None, description="数据来源文件名"),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=500, description="每页条数"),
    user: dict = Depends(require_login),
    db=Depends(get_system_db_dep),
):
    """三层筛选搜索裁量规则"""
    conn, cur = db
    result = await search_rules(
        conn, cur,
        rule_type=rule_type,
        domain=domain,
        keyword=keyword,
        source_file=source_file,
        page=page,
        page_size=page_size,
    )
    return {"success": True, "data": result}


@router.get("/discretion-rules/{rule_id}")
async def get_discretion_rule_detail(
    rule_id: int,
    user: dict = Depends(require_login),
    db=Depends(get_system_db_dep),
):
    """获取单条裁量规则详情"""
    conn, cur = db
    rule = await get_rule_by_id(conn, cur, rule_id)
    if not rule:
        raise HTTPException(status_code=404, detail="裁量规则不存在")
    return {"success": True, "data": rule}
