from typing import Optional
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session

from app.core.database import get_db
from app.models.user import User
from app.schemas.common import ResponseModel, ListResponse
from app.services import masking_service
from app.api.deps import get_current_user, require_admin

router = APIRouter()


@router.get("/rules")
def list_masking_rules(
    level_id: Optional[int] = Query(None),
    category_id: Optional[int] = Query(None),
    page: int = Query(1, ge=1),
    page_size: int = Query(20, ge=1, le=500),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    items, total = masking_service.list_masking_rules(db, level_id=level_id, category_id=category_id, page=page, page_size=page_size)
    return ListResponse(
        data=[{
            "id": r.id,
            "name": r.name,
            "level_id": r.level_id,
            "category_id": r.category_id,
            "algorithm": r.algorithm,
            "params": r.params,
            "is_active": r.is_active,
            "description": r.description,
            "level_name": r.level.name if r.level else None,
            "category_name": r.category.name if r.category else None,
        } for r in items],
        total=total,
        page=page,
        page_size=page_size,
    )


@router.post("/rules")
def create_masking_rule(
    req: dict,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_admin),
):
    item = masking_service.create_masking_rule(db, req)
    return ResponseModel(data={"id": item.id})


@router.put("/rules/{rule_id}")
def update_masking_rule(
    rule_id: int,
    req: dict,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_admin),
):
    db_obj = masking_service.get_masking_rule(db, rule_id)
    if not db_obj:
        from fastapi import HTTPException, status
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="规则不存在")
    item = masking_service.update_masking_rule(db, db_obj, req)
    return ResponseModel(data={"id": item.id})


@router.delete("/rules/{rule_id}")
def delete_masking_rule(
    rule_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(require_admin),
):
    masking_service.delete_masking_rule(db, rule_id)
    return ResponseModel(message="删除成功")


@router.post("/preview")
def preview_masking(
    source_id: int,
    table_name: str,
    project_id: Optional[int] = None,
    limit: int = Query(20, ge=1, le=100),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    result = masking_service.preview_masking(db, source_id, table_name, project_id=project_id, limit=limit)
    return ResponseModel(data=result)
