from fastapi import APIRouter, Depends
from sqlalchemy import or_
from sqlalchemy.orm import Session

from app import models, schemas
from app.database import get_db

router = APIRouter(prefix="/dashboard", tags=["dashboard"])


@router.get("/summary", response_model=schemas.DashboardSummary)
def dashboard_summary(db: Session = Depends(get_db)) -> schemas.DashboardSummary:
    last_task = db.query(models.TaskRun).order_by(models.TaskRun.created_at.desc()).first()
    return schemas.DashboardSummary(
        total_sessions=db.query(models.FeishuSession).count(),
        processed_sessions=db.query(models.FeishuSession)
        .filter(models.FeishuSession.process_status.in_([models.ProcessStatus.pending_review, models.ProcessStatus.completed]))
        .count(),
        pending_review_count=db.query(models.RawQAItem)
        .filter(models.RawQAItem.review_status.in_([models.ReviewStatus.pending, models.ReviewStatus.reviewing]))
        .count(),
        high_risk_count=db.query(models.RawQAItem)
        .filter(or_(models.RawQAItem.risk_level == models.RiskLevel.high, models.RawQAItem.risk_level == models.RiskLevel.forbidden))
        .count(),
        approved_qa_count=db.query(models.RawQAItem).filter(models.RawQAItem.review_status == models.ReviewStatus.approved).count(),
        standard_qa_count=db.query(models.StandardQAItem).count(),
        callable_qa_count=db.query(models.StandardQAItem)
        .join(models.RawQAItem)
        .filter(
            models.StandardQAItem.audit_status == models.AuditStatus.approved,
            models.StandardQAItem.call_status == models.CallStatus.callable,
            models.StandardQAItem.risk_level.in_([models.RiskLevel.low, models.RiskLevel.medium]),
            models.RawQAItem.desensitization_status.in_(
                [models.DesensitizationStatus.done, models.DesensitizationStatus.not_needed]
            ),
        )
        .count(),
        last_task_status=last_task.task_status.value if last_task else None,
        last_task_time=last_task.ended_at if last_task else None,
        last_task_error=last_task.error_message if last_task else None,
    )

