# #region TranslateRunHistoryRoutesModule [C:3] [TYPE Module] [SEMANTICS fastapi, translate, api, history, status, records]
# @defgroup Api Module group.
# @BRIEF Translation Run history, status, records and batches routes.
# @LAYER API
# @RELATION DEPENDS_ON -> [TranslateRunRoutesModule]
# @RELATION CALLED_BY -> [TranslateRoutes]

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

from ....core.config_manager import ConfigManager
from ....core.database import get_db
from ....core.logger import logger
from ....dependencies import get_config_manager, get_current_user, has_permission
from ....plugins.translate.orchestrator import TranslationOrchestrator
from ....schemas.auth import User
from ._helpers import _run_to_response
from ._router import router

from datetime import datetime, UTC


# #region get_run_history [C:4] [TYPE Function]
# @ingroup Api
# @BRIEF Get run history for a translation job.
# @PRE  User has translate.history.view permission.
# @POST  Returns list of runs.
@router.get("/jobs/{job_id}/runs")
def get_run_history(
    job_id: str,
    page: int = Query(1, ge=1),
    page_size: int = Query(20, ge=1, le=100),
    current_user: User = Depends(get_current_user),
    _ = Depends(has_permission("translate.history", "VIEW")),
    db: Session = Depends(get_db),
    config_manager: ConfigManager = Depends(get_config_manager),
):
    logger.reason(f"get_run_history — Job: {job_id}, User: {current_user.username}", extra={"src": "translate_routes"})
    try:
        orch = TranslationOrchestrator(db, config_manager, current_user.username)
        total, runs = orch.get_run_history(job_id, page=page, page_size=page_size)
        return {"items": runs, "total": total, "page": page, "page_size": page_size}
    except ValueError as e:
        raise HTTPException(status_code=http_status.HTTP_404_NOT_FOUND, detail=str(e))
# #endregion get_run_history


# #region get_run_status [C:4] [TYPE Function]
# @ingroup Api
# @BRIEF Get status and statistics for a translation run.
# @PRE  User has translate.history.view permission.
# @POST  Returns run details with statistics.
@router.get("/runs/{run_id}")
def get_run_status(
    run_id: str,
    current_user: User = Depends(get_current_user),
    _ = Depends(has_permission("translate.history", "VIEW")),
    db: Session = Depends(get_db),
    config_manager: ConfigManager = Depends(get_config_manager),
):
    logger.reason(f"get_run_status — Run: {run_id}, User: {current_user.username}", extra={"src": "translate_routes"})
    try:
        orch = TranslationOrchestrator(db, config_manager, current_user.username)
        return orch.get_run_status(run_id)
    except ValueError as e:
        raise HTTPException(status_code=http_status.HTTP_404_NOT_FOUND, detail=str(e))
# #endregion get_run_status


# #region get_run_records [C:4] [TYPE Function]
# @ingroup Api
# @BRIEF Get paginated records for a translation run.
# @PRE  User has translate.history.view permission.
# @POST  Returns paginated records.
@router.get("/runs/{run_id}/records")
def get_run_records(
    run_id: str,
    page: int = Query(1, ge=1),
    page_size: int = Query(50, ge=1, le=500),
    status: str | None = Query(None),
    deduplicate: bool = Query(False, description="Return one row per unique source_hash (cache-like view)"),
    current_user: User = Depends(get_current_user),
    _ = Depends(has_permission("translate.history", "VIEW")),
    db: Session = Depends(get_db),
    config_manager: ConfigManager = Depends(get_config_manager),
):
    logger.reason(f"get_run_records — Run: {run_id}, User: {current_user.username}", extra={"src": "translate_routes"})
    try:
        orch = TranslationOrchestrator(db, config_manager, current_user.username)
        return orch.get_run_records(run_id, page=page, page_size=page_size, status_filter=status, deduplicate=deduplicate)
    except ValueError as e:
        raise HTTPException(status_code=http_status.HTTP_404_NOT_FOUND, detail=str(e))
# #endregion get_run_records


# #region get_batches [C:4] [TYPE Function]
# @ingroup Api
# @BRIEF Get batches for a translation run.
# @PRE  User has translate.job.view permission.
# @POST  Returns list of batches.
@router.get("/runs/{run_id}/batches")
def get_batches(
    run_id: str,
    current_user: User = Depends(get_current_user),
    _ = Depends(has_permission("translate.job", "VIEW")),
    db: Session = Depends(get_db),
):
    logger.reason(f"get_batches — Run: {run_id}, User: {current_user.username}", extra={"src": "translate_routes"})
    try:
        from ....models.translate import TranslationBatch
        batches = (
            db.query(TranslationBatch)
            .filter(TranslationBatch.run_id == run_id)
            .order_by(TranslationBatch.batch_index.asc())
            .all()
        )
        return [
            {
                "id": b.id,
                "run_id": b.run_id,
                "batch_index": b.batch_index,
                "status": b.status,
                "total_records": b.total_records or 0,
                "successful_records": b.successful_records or 0,
                "failed_records": b.failed_records or 0,
                "started_at": b.started_at.isoformat() if b.started_at else None,
                "completed_at": b.completed_at.isoformat() if b.completed_at else None,
                "created_at": b.created_at.isoformat() if b.created_at else None,
            }
            for b in batches
        ]
    except Exception as e:
        logger.explore("get_batches failed", extra={"src": "translate_routes", "error": str(e)})
        raise HTTPException(status_code=http_status.HTTP_400_BAD_REQUEST, detail=str(e))
# #endregion get_batches


# #endregion TranslateRunHistoryRoutesModule
