from typing import Optional
from fastapi import APIRouter, Depends, Query, HTTPException, status
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 compliance_service
from app.api.deps import get_current_user, require_admin

router = APIRouter()


@router.post("/init-rules")
def init_rules(
    db: Session = Depends(get_db),
    current_user: User = Depends(require_admin),
):
    compliance_service.init_builtin_rules(db)
    return ResponseModel(message="初始化完成")


@router.post("/scan")
def scan_compliance(
    project_id: Optional[int] = Query(None),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    try:
        issues = compliance_service.scan_compliance(db, project_id=project_id)
        return ResponseModel(data={"issues_found": len(issues)})
    except Exception:
        import logging
        logging.exception("Compliance scan failed")
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="扫描执行失败，请稍后重试"
        )


@router.get("/issues")
def list_issues(
    project_id: Optional[int] = Query(None),
    status: Optional[str] = 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 = compliance_service.list_issues(db, project_id=project_id, status=status, page=page, page_size=page_size)
    return ListResponse(
        data=[{
            "id": i.id,
            "rule_id": i.rule_id,
            "project_id": i.project_id,
            "entity_type": i.entity_type,
            "entity_name": i.entity_name,
            "severity": i.severity,
            "description": i.description,
            "suggestion": i.suggestion,
            "status": i.status,
            "created_at": i.created_at.isoformat() if i.created_at else None,
        } for i in items],
        total=total,
        page=page,
        page_size=page_size,
    )


@router.post("/issues/{issue_id}/resolve")
def resolve_issue(
    issue_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    issue = compliance_service.resolve_issue(db, issue_id)
    if not issue:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="问题不存在")
    return ResponseModel(message="已标记为已解决")
