# #region TranslateMetricsRoutesModule [C:2] [TYPE Module] [SEMANTICS fastapi, translate, api, search]
# @BRIEF Translation Metrics endpoints.
# @LAYER API


from fastapi import Depends, HTTPException, Query, status
from sqlalchemy.orm import Session

from ....core.database import get_db
from ....core.logger import logger
from ....dependencies import get_current_user, has_permission
from ....plugins.translate.metrics import TranslationMetrics
from ....schemas.auth import User
from ._router import router

# ============================================================
# Metrics
# ============================================================

# #region get_metrics [C:4] [TYPE Function]
# @BRIEF Get translation metrics, optionally filtered by job.
# @PRE  User has translate.metrics.view permission.
# @POST  Returns metrics data.
@router.get("/metrics")
async def get_metrics(
    job_id: str | None = Query(None),
    current_user: User = Depends(get_current_user),
    _ = Depends(has_permission("translate.metrics", "VIEW")),
    db: Session = Depends(get_db),
):
    """Get translation metrics."""
    logger.reason(f"get_metrics — User: {current_user.username}", extra={"src": "translate_routes"})
    try:
        metrics_svc = TranslationMetrics(db)
        if job_id:
            return metrics_svc.get_job_metrics(job_id)
        return metrics_svc.get_all_metrics()
    except ValueError as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
# #endregion get_metrics


# #region get_job_metrics [C:4] [TYPE Function]
# @BRIEF Get aggregated metrics for a specific job.
# @PRE User has translate.metrics.view permission.
# @POST Returns metrics dict.
# @COMPLEXITY 4

@router.get("/jobs/{job_id}/metrics")
async def get_job_metrics(
    job_id: str,
    current_user: User = Depends(get_current_user),
    _ = Depends(has_permission("translate.metrics", "VIEW")),
    db: Session = Depends(get_db),
):
    """Get aggregated metrics for a specific job."""
    logger.reason(f"get_job_metrics — Job: {job_id}, User: {current_user.username}", extra={"src": "translate_routes"})
    try:
        metrics_svc = TranslationMetrics(db)
        return metrics_svc.get_job_metrics(job_id)
    except ValueError as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
# #endregion get_job_metrics

# #endregion TranslateMetricsRoutesModule
