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 risk_service
from app.api.deps import get_current_user

router = APIRouter()


@router.post("/recalculate")
def recalculate_risk(
    project_id: Optional[int] = Query(None),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    if project_id:
        result = risk_service.calculate_project_risk(db, project_id)
        return ResponseModel(data={"project_id": project_id, "risk_score": result.risk_score if result else 0})
    result = risk_service.calculate_all_projects_risk(db)
    return ResponseModel(data=result)


@router.get("/top")
def risk_top(
    entity_type: str = Query("project"),
    n: int = Query(10, ge=1, le=100),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    items = risk_service.get_risk_top_n(db, entity_type=entity_type, n=n)
    return ListResponse(
        data=[{
            "id": r.id,
            "entity_type": r.entity_type,
            "entity_id": r.entity_id,
            "entity_name": r.entity_name,
            "risk_score": r.risk_score,
            "sensitivity_score": r.sensitivity_score,
            "exposure_score": r.exposure_score,
            "protection_score": r.protection_score,
            "updated_at": r.updated_at.isoformat() if r.updated_at else None,
        } for r in items],
        total=len(items),
        page=1,
        page_size=n,
    )


@router.get("/projects/{project_id}")
def project_risk(
    project_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    from app.models.risk import RiskAssessment
    item = db.query(RiskAssessment).filter(
        RiskAssessment.entity_type == "project",
        RiskAssessment.entity_id == project_id,
    ).first()
    if not item:
        return ResponseModel(data=None)
    return ResponseModel(data={
        "risk_score": item.risk_score,
        "sensitivity_score": item.sensitivity_score,
        "exposure_score": item.exposure_score,
        "protection_score": item.protection_score,
        "details": item.details,
        "updated_at": item.updated_at.isoformat() if item.updated_at else None,
    })
